Get you started Python (Flask-based web App) learning

Source: Internet
Author: User
Tags response code
Flask is a very good web framework, its biggest feature is to maintain a simple and easy to expand the small core, the others have their own grasp, and easy to replace, and even, you can see in the community of many open source, can be directly used in the production environment of the expansion. So far, I believe about his introduction and very much, even if the cnblog, a random search will have a lot of content, but still a point, it is a self-summary

Deployment environment

Install Python

First of all, of course to install the Python environment, go to the official website to download the latest environment (I choose the latest 3.6 version)

Then go all the way to the next step, take note or select the installation path.

Environment variables

The next configuration environment variable is almost the same as Java, after path;.; Enter the path of the Python installation, and then again; Enter the scripts folder under the Python directory, using some tools from the PY (such as PIP)

Installing flask

After configuring the PIP, it is easy to install flask, enter cmd into the console, and enter the following command:

pip3.6 Install flask

Development tools

工欲善其事 its prerequisite, the choice of development tools is very important, I choose is pycharm, can also be downloaded from the official website, and please make Ji with Huo is Fang version Shi

Start development

First, open pycharm and create a pure Python project:

After the project has been created, some are just an empty project, and create a PY file has been developed, under the project folder right-New-->python file and then take a name, I get the name of default, the directory folder will be created under the default.py file.

Preliminary study on Flask

Enter the code on this file (assuming the installation flask has succeeded):


From flask import Flask #导入Flask类app =flask (__name__) #创建Flask类的一个实例if __name__== ' __main__ ': #Python入口程序  App.run ( Debug=true) #使其运行于本地服务器上

This is the directory where you can switch the CMD console to the project directory and enter the command:

Python default.py

When you import the Flask class, the WSGI program is created automatically when you run the script

The display is correct:

When prompted, enter the default address of flask in the browser, as shown below:

Because there are no pages yet, all access to any address is 404

Description
Debug=true representative running in debug mode, debugging mode absolutely can not be used in production environment!!!

Routing

The following creates a default route for this app, Flask uses adorners for routing configuration:


@app. Route ("/") def index (): Return "

At this point, the page reads as follows:

Output the contents of the return, and at this point the console displays:

The status code is 200 and no longer is 404

The adorners here can be understood as annotations in Java for the time being and discussed in detail at a later stage, while the use of this route can be temporarily understood as the annotated routing of the servlet in EE.

Routed with parameters

Flask also supports routing with parameters:


@app. Route ("/user/<name>") def user (name): Return "

In the browser, enter:

127.0.0.1:5000/user/niufen

This is entered as:

About the route to say so much for the time being, then go to the CMD console, CTRL + C exit the server, enter Python, enter the python command line interface, you can execute various PY statements

Then import the App object under the Default.py object in this interface:

From the default Import app

Then enter, at which point you can use the App object on the command line and type:

App.url_map

My display is as follows:

As can be seen, using a map to store all the routes under this object, and from the content can be seen all get way, note that the static, is stored in the file, the piece, by the way, this also embodies the flask a feature, that is, it has a number of configuration options, But basically in the initial state there is a definite default value, such as the template in templates, the picture in static, although this configuration can be modified, but not recommended, especially at the beginning.

From the default Import app this line of code represents the import of the app from the default object and can be used directly under the app, as well as the previous code from flask import Flask

There are two ways to import in Python, import direct import and from ... imports, specific differences to see the PY basic syntax

If you want to make the route post, it's also simple:


@app. Route ("/user", methods=["POST"]) def user (): Name=request.args.get ("name") return "

Can

Request context

Flask also has a request context object, which is requests, such as:


From flask Import Request #页头 Importing Request Object @app.route (/req_test) def req_test (): val= "" For Key,value in Request.args.items ( ): val+= "%s =%s <br>"% (Key,value) return Val;

After entering exit () in the console, continue entering the Python default.py into the server

At this point, enter the URL in the browser:

127.0.0.1:5000/req_test?age=5&name=abc

The browser appears as:

Test Code 2 (assuming you have imported the Request object):


@app. Route (/req_test) def req_test (): val= "" For Key,value in Request.headers.items (): val+= "%s =%s <br>"% (key,val UE) return Val;

The browser appears as:

Flask comes with a system context of a total of four:

Current_app is approximately equal to application
G an object for temporary storage is approximately equal to ViewBag
The request is roughly the same as the servlet or ASP.
The session is roughly the same as the servlet or ASP.

Response

The flask response can use the Make_response object, similar to the usage in the Java servlet:


From flask import make_response #页头, import Make_response object @app.route ("/res_test") def res_test (): Response=make_response (" 

The content of this code is to set the cookie at the time of the response
Enter the address in the browser:

127.0.0.1:5000/res_test

Appear as bold Hello World on the page, but you can view the browser and find that the response has been stored in the browser's cookie

Other common functions: jump

In web development, often encounter direct jump, flask also provides the redirect method to achieve:


From Flask Import Redirect # page header, import redirect Object @app.route ("/") def index (): Return redirect ("www.baidu.com/")

At this point, the visit will jump directly to Baidu

Other common functions: Response code

The normal response code can be used directly after the return string, such as:


@app. Route ("/") def index (): Return "

The results of the visit are as follows:


As you can see, although the page appears unchanged at this time, the response code is 400

The error code flask also provides a proprietary function:


From flask import Abort #导入abort对象 @app. Route ('/user/<name> ') def user (name): if name = = ' Test ': Abort (All) return "&L T;h1>hello%s!

The function of this code is that when the value of name is test Yes, the error code 500 is returned, note that the page does not display content at this time, because the program is not controlled by the code, and control is given to the system.

At this point, flask basic knowledge has been finished, now can do some simple procedures, but certainly not do so, like only with Servlets, not JSP pages or other templates can make a very beautiful system, but most still need JSP page or other template page as support, The next chapter explains how to use the JINJA2 template engine and the WTF form plug-in in your system.

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.