Using flask as an example to explain how Python's framework is used

Source: Internet
Author: User
Understanding the WSGI framework, we found that: in fact, a Web App is to write a WSGI processing function that responds to each HTTP request.

But how to handle HTTP requests is not a problem, but the question is how to handle 100 different URLs.

Each URL can correspond to get and post requests, and of course, put, delete, and so on, but we usually only consider the most common get and post requests.

One of the simplest ideas is to remove the HTTP request information from the Environ variable and then judge it individually:

def application (environ, Start_response):  method = environ[' Request_method ']  path = environ[' Path_info ']  if method== ' GET ' and path== '/':    return handle_home (environ, start_response)  if method== ' POST ' and path= '/ Signin ':    return Handle_signin (environ, start_response)  ...

Just write down the code is definitely not maintenance.

The reason why the code cannot be maintained is that the interface provided by WSGI is more advanced than the HTTP interface, but compared to the web app's processing logic, we need to be more abstract on the Wsgi interface, so we can focus on a function to process a URL. As for the URL-to-function mapping, it is given to the web framework.

Because it is easy to develop a web framework in Python, Python has hundreds of open-source web frameworks. Here we do not discuss the advantages and disadvantages of various web frameworks, directly choose a more popular web framework--flask to use.

Writing a web App with flask is simpler than WSGI interface (this is not nonsense, if it is more complicated than WSGI, why use the framework?) ), we first install the flask with Easy_install or PIP:

$ Easy_install Flask

Then write a app.py, processing 3 URLs, respectively:

    1. GET/: Home, back home;
    2. Get/signin: Login page, display login form;
    3. Post/signin: Processes the Login form and displays the results of the login.

Note Oh, the same url/signin has get and post two requests, which are mapped to two processing functions.

Flask automatically associates URLs and functions internally through the Python adorner, so the code we write is like this:

From flask import flaskfrom flask Import Requestapp = Flask (__name__) @app. Route ('/', methods=[' GET ', ' POST ') def home (): C0/>return '

Home

' @app. Route ('/signin ', methods=[' GET ']) def signin_form (): return "" @app. Route ('/signin ', methods=[' POST ') def signin (): # need to read form contents from Request object: if request.form[' username ']== ' admin ' and request.form[' password ']== ' Password ': return '

Hello, admin!.

' return '

Bad username or password.

' If __name__ = = ' __main__ ': app.run ()

The server running Python app.py,flask is listening on port 5000:

$ python app.py  * Running on Http://127.0.0.1:5000/Try

Open the browser, enter the home address http://localhost:5000/:

The homepage is displayed correctly!

Then enter Http://localhost:5000/signin in the browser address bar to display the login form:

Enter the default username admin and password password, login successful:

Enter the user name and password for another error, Login failed:

The actual web app should get the user name and password, go to the database query and then compare, to determine whether the user can log on successfully.

In addition to flask, the common Python web framework is:

    • Django: All-purpose web framework;
    • web.py: a small web framework;
    • Bottle: Web framework similar to flask;
    • Tornado:facebook's Open source asynchronous web framework.

Of course, because it's not difficult to develop a Python web framework, we'll develop a web framework on our own.
Summary

With web frameworks, when we write Web applications, our attention shifts from WSGI processing functions to url+ corresponding handlers, which makes it much easier to write web apps.

In addition to configuring URLs, it is important to get user data from HTTP requests when writing URL handlers. Web frameworks provide their own APIs to implement these features. Flask to get the contents of the form by request.form[' name '].

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.