Flask Chinese Documents
Flask_login Documentation
Flask-sqlalchemy Documentation
Jinja2 Template Document
To familiarize yourself with Python's WEB development, find this framework. Here is a note to use it to write a simple login Demo function during the problem encountered.
The above links are used to document the relevant library.
Flask_login This is the official implementation of a set of login verification library.
Flask_sqlalchemy is an official encapsulation of the SQLAlchemy library, which is an ORM for database access.
The development tool used here is Pycharm, which allows you to create a Flask project directly with this tool.
First, from a simple example.
Create a run.py code file that resides in the root directory of the project.
run.py
from Import = Flask (__name__) @app. Route ('/')def Hello_world (): return ' Hello world! ' if __name__ ' __main__ ' : app.run ()
This is one of the simplest and most straightforward applications on official documents.
Here are two places to note:
[Email protected] (‘/‘)
The definition here is a complete route, that is, the "/" is now defined, then the real access address is the home page.
2.app objects
Everything you do in this object is globally valid.
Example: I want to do some initialization before all the requests are started , so I can use the App object directly to define
@app. Before_request def before_request (): Pass
The complete code is:
from Import = Flask (__name__) @app. Before_requestdef before_request (): Passif__name__'__main__': app.run ()
Second, create the application
According to the official documentation, the directory structure for large applications is:
/yourapplication /runserver.py /yourapplication /__init__. PY /views.py /static /style.css /templates layout.html index.html login.html ...
So, to create an app's directory at the root of the project, create a demo app, and delete the static and templates folders under the root directory.
In the demo directory, create 3 files, respectively: "__init__.py", "config.py", "Requirements.txt".
__init__.py This is not much to say.
config.py This is the configuration information for Flask.
Requirements.txt This is used for the convenience of Python import libraries.
Add the following to the Requirements.txt file, these are the libraries to use.
flaskflask-sqlalchemyflask-loginflask-wtfpygmentspymysql
Three, Packaging SQLAlchemy Library
1. Add the following configuration in the config.py file
DEBUG =='mysql+pymysql://root:[email protected]/test?charset=utf8' '*\xff\x93\xc8w\x13\[email protected]\xd6\x82\x0f\x84\x18\xe7\xd9\\|\x04e\xb9 (\xfd\xc3 '
Configuration parameters See here
2. Create a common directory under the demo directory, as a public library, and create a data.py file in this directory
Using Fetchall () is the result of getting the SQL script back, and rowcount is the number of rows that are affected.
#Config=utf-8 fromSQLAlchemyImportCreate_engine fromSqlalchemy.sqlImporttext fromDemo.configImportSqlalchemy_database_uri, Sqlalchemy_echodefDb_query (SQL, Settings=none, echo=None):"""perform additions and deletions to SQL statement Args:sql:SQL statement settings: Database connection string echo: Output SQL statement Returns: Execute knot Fruit""" ifSettings isnone:settings=Sqlalchemy_database_uriifEcho isNone:echo=Sqlalchemy_echoreturnCreate_engine (Settings, echo=echo). Connect (). Execute (text (SQL)). Fetchall ()defDb_execute (SQL, Settings=none, echo=None):"""perform additions and deletions to SQL statement Args:sql:SQL statement settings: Database connection string echo: Output SQL statement Returns: Affect row Number""" ifSettings isnone:settings=Sqlalchemy_database_uriifEcho isNone:echo=Sqlalchemy_echoreturnCreate_engine (Settings, echo=echo). Connect (). Execute (text (SQL) ). RowCount#Test Code#SELECT * from Py_user#INSERT into Py_user (name) VALUES (' 123456 ')#data = Db_query ("SELECT * from Py_user")#print (data)
3. Create a __init__.py file in the common directory
__init__.py:
# Config=utf-8 from Import SQLAlchemy __all__ = ['db'= SQLAlchemy ()
This code is used to register this data access library.
Iv. Initializing applications
To the app to register the database, as well as the incoming configuration information, it is important to note that there is a need to open a file to do these things, can not be fully written in the run.py file, because later in the use of other libraries, here to register, but in the real use of the generated object is called here, At this time, two files import each other and there will be an exception.
As a result, the ability to create an App object in run.py is extracted to the __init__.py file in the demo directory.
/demo/__init__.py
#Config=utf-8 fromFlaskImportFlask fromDemo.commonImportDBdefCreate_app (config_filename=None): App= Flask (__name__) ifConfig_filename is notNone:#Registering data access informationapp.config.from_pyfile (config_filename)#Initializing the databaseconfigure_database (APP)returnappdefconfigure_database (APP):"""initializes the database connection. Args:app: Apply object. Returns: The function has no return value. """Db.init_app (APP)
The code in the/run.py file is modified to
#Config=utf-8 fromDemoImportCreate_appapp= Create_app ('config.py') @app. Before_requestdefbefore_request ():"""here is the global method, called before the request begins. Where flask has a global variable G, it is the same as the session, you can use it to save the current user's data Returns:""" Passif __name__=='__main__': App.run ()
Use the Flask framework to write the user login function of the demo when encountered by various pits (a)--Create an application