Python + Flask Framework Program Demo Getting Started
This example uses a blueprint Flask + + Flask-Login + SQLAlchemy + WTForms + PyMySQL associated schema
Flask Web Framework Introduction
Flask micro web framework, the framework itself is very lean, does not mean that function of the weak microcomputer, the core code based Werkzeug, Jinja 2 both libraries, be it in the form of plug-in extensions, and is easy to install and use of plug-ins, and may itself development extensions
Similar to other web frame, flask request (request), the route (route), the response (response) constitute a substantially complete http process.
flask popular main reasons:
- It has a very complete official documents, very easy to get started
- There are very good expansion mechanism and the expansion of third-party environment, working in common software has a corresponding expansion of yourself is also very easy to achieve expansion
- In the form of miniature frame it gives developers greater choice
Introduction blueprint
Modular applications can be implemented using Blueprint (Blueprint) in Flask project, a blueprint allows the application level clearer and easier for developers to maintain and develop the project. Blueprint will act on the same request URL address prefix, the request with the same prefix are placed in a module, so find the problem, see a route to quickly find the corresponding view, and solve the problem.
Blueprint provides a template filter, static files, templates, and other functions
Flask extensions
Flask-Login库
Flask-Login by user session, log on to provide common tasks, such as login (logging in), logout (logging out) and the current user (current user)
login_user () function: the user's sign implemented, in the general call sign view function
logout_user () function: to achieve logout function
current_user property: Gets the current user
for the user, if desired page is visible to authorized users, plus @login_required decorator to declare before the appropriate view function, @ login_required decorator for not logged in user access, default processing is redirected to the specified view LoginManager.login_view
Flask-Script库
Provides insertion of an external script to Flask, including running a server with the development of a custom Python shell, set the script database, cronjobs, and other web applications run outside the command-line tasks; making scripts and systems separately;
Flask Flask Script and similar work itself, simply define and add a command from the command line by calling instance Manager;
WTForms form
WTForms is a support frame form a plurality of web components, mainly used for user authentication data request.
Simple code example:
Myvalidators class (Object): '' 'custom validation rules' '' DEF the __init __ (Self, Message): self.message = Message DEF the __call __ (Self, form, Field): Print (field.data, "information input by the user ") IF field.data ==" Haiyan ": return None The raise validators.ValidationError (self.message) class the LoginForm (Form1): '' 'Form1' '' name = simple.StringField ( label =" user name ", the widget widgets.TextInput = (), validators = [ Myvalidators (Message = "user name must be haiyan"), # may be the custom regular validators.DataRequired (message = "user name can not be blank"), validators.Length (max = 8, min = 3, message = "Username must be greater than% (max) d and less than% (min) D ") ], render_kw = { "class": " form-control"} # set properties ) pwd = simple.PasswordField ( label = "password", validators = [ validators.DataRequired (Message = "password is not blank"), validators.Length ( max = 8, min = 3, message = " password must be longer than% (max) d and less than% (min) D"), validators.Regexp (REGEX = "\ D +", Message = "password must be a number") , ], the widget = widgets.PasswordInput (), render_kw = { "class": "form-Control"} ) @ app.route ( '/ Login', Methods = [ "the GET", "the POST"]) form = LoginForm(formdata=request.form) if form.validate(): DEF Login (): if request.method =="GET": form = LoginForm() the render_template return ( "the login.html", form = form) the else: Print ( "user-submitted data format used validation value:% S"% form.data) return "login is successful" the else: Print (form.errors , "error message") return render_template ( "login.html", form = form)
login.html
<body> <form action="" method="post" novalidate> <p>{{ form.name.label }} {{ form.name }} {{ form.name.errors.0 }}</p> <p>{{ form.pwd.label }} {{ form.pwd }} {{ form.pwd.errors.0 }}</p> <input type="submit" value="提交"> <!--用户名:<input type="text">--> <!--密码:<input type="password">--> <!--<input type="submit" value="提交">--> </form> </body>
SQLAlchemy
SQLAlchemy is a very powerful relational database framework that supports multiple databases background. SQLAlchemy provides a high-level ORM, also provides the use of native SQL database low-level functions.
ORM: the operation will be converted to native SQL objects
The advantages of
ease of use, can effectively reduce duplication SQL
performance loss less
flexible design, complex queries can easily achieve
good portability
Sample Code
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class Student(db.Model): s_id = db.Column(db.Integer, primary_key=True, autoincrement=True) s_name = db.Column(db.String(16), unique=True) s_age = db.Column(db.Integer, default=1) __tablename__ = "student"
among them:
S_id type Integer represents the creation of the field of plastic surgery,
primary_key indicates whether the primary key
It indicates that the field is a string String
The only unique indicates that the field
default indicates the default value
autoincrement indicates whether the increment
The last code address
github project code Address: sample project Address
Project operating results Screenshot