Using Flask as an example to explain how to use the Python framework

Source: Internet
Author: User
Tags python decorator
This article mainly introduces how to use the Python framework. This article describes how to install the Flask framework. the code is based on Python2.x. if you need it, you can refer to the WSGI framework, we found that a Web App is actually writing a WSGI processing function to respond to each HTTP request.

But how to handle HTTP requests is not a problem. The question is how to handle 100 different URLs.

Each URL can correspond to GET and POST requests. of course, there are PUT and DELETE requests, but we usually only consider the most common GET and POST requests.

The simplest idea is to retrieve the HTTP request information from the environ variable and determine one by one:

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)  ...

It's just that you cannot maintain the code.

The reason why the code cannot be maintained is that WSGI provides a lot of interfaces that are more advanced than HTTP interfaces, but it is still relatively low compared with the processing logic of Web apps, we need to be further abstracted on the WSGI interface. let's focus on processing a URL with a function. as for URL-to-function ING, we will hand it over to the Web framework.

Since it is very easy to develop a Web framework with Python, Python has hundreds of open-source Web frameworks. Here we will not discuss the advantages and disadvantages of various Web frameworks. we will directly select a popular Web framework-Flask.

Using Flask to write Web apps is simpler than WSGI interfaces (isn't it nonsense? if it is more complicated than WSGI, what should I do with the framework ?), We first use easy_install or pip to install Flask:

$ easy_install flask

Then write an app. py and process the three URLs:

  1. GET/: Home page, return Home;
  2. GET/signin: logon page. the logon form is displayed;
  3. POST/signin: process the logon form and display the logon result.

Note: the same URL/signin has two types of requests: GET and POST, which are mapped to two processing functions.

Flask automatically associates the URL with the function internally through the Python decorator. Therefore, the code we write is like this:

From flask import Flaskfrom flask import requestapp = Flask (_ name _) @ app. route ('/', methods = ['GET', 'post']) def home (): return 'home' @ app. route ('/signin', methods = ['get']) def signin_form (): return ''' @ app. route ('/signin', methods = ['post']) def signin (): # you need to read the form content from the 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 ()

Run python app. py, and the Server that comes with Flask listens on port 5000:

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

Open your browser and enter the home address http: // localhost: 5000 /:

The homepage is displayed correctly!

Enter http: // localhost: 5000/signin in the address bar of the browser to display the logon form:

Enter the default username admin and password. the logon is successful:

Enter another wrong user name and password. logon failed:

The actual Web App should obtain the user name and password, go to the database for query, and then compare to determine whether the user can log on successfully.

In addition to Flask, common Python Web frameworks include:

  • Django: all-embracing Web framework;
  • Web. py: a small Web framework;
  • Bottle: a Web framework similar to Flask;
  • Tornado: Facebook's open-source asynchronous Web framework.

Of course, it is not difficult to develop a Python Web framework. we will also develop a Web framework ourselves later.
Summary

With the Web framework, when writing a Web application, our attention is shifted from the WSGI processing function to the corresponding processing function of URL +. in this way, it is easier to write a Web App.

When writing URL processing functions, in addition to configuring URLs, it is also very important to get user data from HTTP requests. The Web framework provides its own APIs to implement these functions. Flask uses request. form ['name'] to obtain the content of the form.

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.