Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the use of flask interface

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "what is the use of the flask interface". The explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the use of the flask interface"?

Flask interface debugging sharp weapon

Here is the first example given to us by the Flask home page, which we'll start with now to gain an in-depth understanding of how "@ app.route ()" works.

Python

Import flaskfrom flask import Flaskapp = Flask (_ _ name__) @ app.route ("/") def hello (): return "Hello World!"

To understand how "@ app.route ()" works, we first need to take a look at the decorator in Python (the one that starts with "@", followed by the function definition). @ app.route and other decorators

What on earth is a decorator? Nothing special. The decorator is just a function that accepts the function (the one you decorate with the "@" symbol) and returns a new function.

When you decorate a function, it means that you tell Python that you are calling the new function returned by your decorator, not just directly returning the execution result of the original function body.

Don't you understand? Here is a simple example:

Python

# This is our decoratordef simple_decorator (f): # This is the new function we're going to return # This function will be used in place of our original definition def wrapper (): print "Entering Function" f () print "Exited Function" return wrapper@simple_decoratordef hello (): print "Hello World" hello ()

Now we know a little bit about how to create our own "@ app.route ()" decorator, but you may notice that our simple_decorator does not accept any parameters, but "@ app.route ()" does. Running the above code outputs the following result:

Entering Function

Hello World

Exited Function

Fine!

So how can we pass parameters to our decorator? To do this, we just need to create a "decorator_factory" function, which we call to return the decorator that applies to our function. Now let's see if we implement it.

Python

Def decorator_factory (enter_message, exit_message): # We're going to return this decorator def simple_decorator (f): def wrapper (): print enter_message f () print exit_message return wrapper return simple_decorator@decorator_factory ("Start", "End") def hello (): print "Hello World" hello ()

Put "app" into "app.route" and give us the output:

Start

Hello World

End

Notice that when we write @ decorator_factory ("Start", "End"), we actually call the decorator_factory function, and the actual returned decorator is already in use, and the code is neat, right?

Now that we have all the pre-knowledge of how the decorator works, we can reimplement this part of Flask API, so turn our attention to the importance of "app" in our Flask applications.

Before we begin to explain what's going on in the Flask object, let's create our own Python class, NotFlask.

Python

Class NotFlask (): passapp = NotFlask ()

Python this is not a very interesting class, but it is worth noting that the methods of this class can also be used as decorators, so let's make this class a little more interesting and add a method called route, which is a simple decorator factory.

Class NotFlask (): def route (self, route_str): def decorator (f): return f return decoratorapp = NotFlask () @ app.route ("/") def hello (): return "Hello World!"

The biggest difference between this decorator and the ones we created before is that we don't want to modify the behavior of the function we decorate, we just want to get a reference to it.

So, the final step is that we intend to take advantage of a feature that uses a by-product of the decorator function to save a link between the paths provided to us, and the decorator function should be associated with it.

To achieve this, we add a "routes" dictionary to our NotFlask object, and when our "decorator" function is called, the path will be inserted into the corresponding position of the function in the new dictionary.

Python

Class NotFlask (): def _ init__ (self): self.routes = {} def route (self, route_str): def decorator (f): self.routes [route _ str] = f return f return decoratorapp = NotFlask () @ app.route ("/") def hello (): return "Hello World!"

Python, we're almost done now! But what's the use of saving a dictionary of paths if you can't access the internal view function? Let's add a method serve (path) that runs a function when a given path exists and gives me the result, and throws an exception when the path is not yet registered.

Python in this series we only focus on reproducing the friendly API provided by the hot door library, so the hook "serve" method to implement a HTTP server is actually a little beyond the scope of this article, of course, the result is certain, run the following segment:

Class NotFlask (): def _ init__ (self): self.routes = {} def route (self, route_str): def decorator (f): self.routes [route _ str] = f return f return decorator def serve (self) Path): view_function = self.routes.get (path) if view_function: return view_function () else: raise ValueError ('Route "{}" has not been registered'.format (path)) app = NotFlask () @ app.route ("/") def hello (): return "Hello World!" app = NotFlask () @ app.route ("/") def hello (): Return "Hello World!" print app.serve ("/")

We will see:

Hello World!

We have completed a very simple reproduction of the first example on the Flask page. Let's write some quick tests to check whether the "@ app.route ()" of our simple reproduction of Flask is correct.

Python

Class TestNotFlask (unittest.TestCase): def setUp (self): self.app = NotFlask () def test_valid_route (self): @ self.app.route ('/') def index (): return 'Hello World' self.assertEqual (self.app.serve' /') 'Hello World') def test_invalid_route (self): with self.assertRaises (ValueError): self.app.serve (' / invalid')

Absolutely right! So, just a simple decorator that contains a dictionary reproduces the basic behavior of Flask's "app.route ()" decorator. Take a breath.

The next article in this series, and the last article in Flask's app.route (), will explain how dynamic URL schemas work by parsing the following example.

Python

App = Flask (_ _ name__) @ app.route ("/ hello/") def hello_user (username): return "Hello {}!" .format (username)

The decorator gets the function run time

Def metric (fn): @ functools.wraps (fn) def f (arg,**kw): start=round (time.time () 1000) fun=fn (arg,**kw) end=round (time.time () 1000) print ('% s executed in% s ms'% (fn.name) End-start)) return fun return f@metricdef test1 (): time.sleep (0.1) print ('hello') @ metricdef test2 (): time.sleep (0.01) print (' hello') test1 () test2 () from flask import Flask Requestapp = Flask (_ _ name__) @ app.route ('/') def hello (): return 'Hello world'if _ _ name__ =' _ _ main__': app.run (host='0.0.0.0', debug=True, port=5555)

Run the above code locally, open a browser to visit http://localhost:5555/, and you can see that the page outputs Hello World!

Flask reference link, reference link 1 get live post in flask, simple tutorial with postman,postman

Note that the return value of pi () cannot be a floating point number, so you must use str to convert to a string, run python flask_pi.py, open a browser to access http://localhost:5000/pi?n=1000000, and you can see the page output of 3.14159169866, which is very close to pi.

If you take a closer look at the code, you will also notice a special variable, request, which appears to be a global variable. It is very strange to get the current request parameters from the global variable. In a multithreaded environment, how do you ensure that each thread gets the request parameters that the current thread is processing? So it cannot be a global variable, it is a thread local variable, and there is no difference between the thread local variable and the global variable in appearance, but when accessing the thread local variable, each thread gets the object shared within the current thread.

From flask import Flask, request,jsonify,url_forapp = Flask (_ _ name__) import mathimport threadingclass PiCache (object): def _ _ init__ (self): self.pis = {} self.lock = threading.RLock () def set (self,n,result): with self.lock: self.pis [n] = result def get (self N): with self.lock: return self.pis.get (n) cache = PiCache () @ app.route ('/') def pi (): n = int (request.args.get ('n') '100') with app.test_request_context (): print (url_for (' pi')) # returns the first parameter in the pi function URL = route / result = cache.get (n) if result: return jsonify ({'cached':True,'result':result}) s = 0.0 for i in range (1) N): s + = 1.0/i/i result = math.sqrt (6yrs) cache.set (nMagazine result) return jsonify ({'cached':False,'result':result}) if _ _ name__ = =' _ main__': app.run ()

The first time:

{"cached": false, "result": 3.1319807472443624}

The second time:

{"cached": true, "result": 3.1319807472443624}

From flask import Flask, request,jsonifyimport redisapp = Flask (_ name__) import mathimport threadingclass PiCache (object): def _ _ init__ (self,client): self.client = client def set (self,n,result): self.client.hset ('pis',str (n), str (result)) def get (self,n): result = self.client.hget (' pis') Str (n) if not result: return return float (result) client = redis.StrictRedis (host='127.0.0.1', port=6379,db ='0') cache = PiCache (client) @ app.route ('/') def pi (): n = int (request.args.get) print (n) result = cache.get (n) if result: return jsonify ({'cached':True) 'result':result}) s = 0.0 for i in range (1Magol n): s + = 1.0/i/i result = math.sqrt (6 seconds) cache.set (n cached':False,'result':result result) return jsonify ({' cached':False,'result':result}) if _ _ name__ = ='_ main__': app.run ()

Run python flask_pi.py, open a browser to access http://localhost:5000/pi?n=1000000, and you can see the page output

First result:

{"cached": false, "result": 3.1319807472443624}

The second result:

{"cached": true, "result": 3.1319807472443624}

Restart the process, refresh the page again, and the output cached field of the reader page is still true, indicating that the cached result is no longer lost because the process is restarted.

MethodView

Friends who have written about Django may ask if Flask supports API writing in the form of classes, and the answer is yes. Let's rewrite the above service using MethodView, which is natively supported by Flask.

From flask import Flask, request,jsonifyfrom flask.views import MethodViewapp = Flask (_ _ name__) import mathimport threadingclass PiCache (object): def _ _ init__ (self): self.pis = {} self.lock = threading.RLock () def set (self,n,result): with self.lock: self.pis [n] = result def get (self N): with self.lock: return self.pis.get (n) cache = PiCache () class PiAPI (MethodView): def _ _ init__ (self,cache): self.cache = cache def get (self,n): result = self.cache.get (n) if result: return jsonify ({'cached':True 'result':result}) s = 0.0 for i in range (1, n): s + = 1 / I / I result = math.sqrt (6 * s) self.cache.set (n, result) return jsonify ({' cached': False, 'result':result})' 'as_view provides parameters that can be directly injected into the constructor of MethodView. We no longer use request.args.keys (). Instead, you put the parameters directly into the URL. This is the RESTFUL style of URL'''app.add_url_rule ('/ pi/',view_func=PiAPI.as_view ('pi',cache)) if _ _ name__ =' _ main__': app.run ()

Then when calling, type: http://127.0.0.1:5000/pi/20 directly in the browser

Results:

{"cached": false, "result": 3.092245052300697} Thank you for reading, the above is the content of "what is the use of flask interface". After the study of this article, I believe you have a deeper understanding of the use of flask interface, and the specific use needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report