Common expansion packs in the Python framework Learning flask

Source: Internet
Author: User

The flask framework is a very extensible framework, so it has a very high number of expansion packs. The capabilities of these expansion packs are powerful. This section summarizes some of the commonly used expansion packs.

First, Flask-script

Pip Install Flask-script

Role:

1. You can let us start the server from the command line, and we can manually specify parameters, such as Ip,port.

Python hello.py runserver-h 127.0.0.1-p 6666

2. Combining the Flask-migration expansion pack enables the migration of data

Second, FLASK-WTF

The role is to be able to better handle Web forms. Forms include: Form labels, form fields, form buttons.

The wtforms is encapsulated in FLASK-WTF, in addition to the ability to process forms, as well as the functionality of form data validation

Common standard fields:

Stringfield: Text field, equivalent to the input tag Type=text

Textareafield: Multiple text fields,

Passwordfield: Password text box

HiddenField: Hidden fields, often used to hide Csrf_token

Selectfield: down list field

Submitfield: Submitting form fields

Filefield: File Upload field

Common validation functions:

DataRequired (): Make sure there is data in the field

Equalto (): Compares the values of two fields for password checking

Length (): validates input string lengths

Numberrange (): Verifies that the value entered is within the range of numbers

URL (): Verify URL

AnyOf (): Verify that the input values are in the optional list

 

Note: The Secret_key parameter must be set to use the expansion pack.

  

1  fromFlaskImportFlask, Render_template2 3  fromFlask_scriptImportManager4  fromFlask_wtfImportFlaskform5  fromWtformsImportStringfield, Passwordfield, Submitfield6  fromWtforms.validatorsImportdatarequired, Equalto7 8  fromSettingsImportMyconfig9App = Flask (__name__)Ten  One #configuration information in the main settings configuration parameters, Secret_key A App.config.from_object (myconfig) - #use the manager to replace the app's startup function -Manager =Manager (APP) the  -  - classMyForm (flaskform): -     """Customizing a Form Class""" +     #define a text label and verify that the data is empty -U_name = Stringfield (validators=[DataRequired ()]) +     #Define a password box to determine if the password is equal Apasswd = Passwordfield (validators=[datarequired (), Equalto ('confirm_passwd')]) atCONFIRM_PASSWD = Passwordfield (validators=[DataRequired ()]) -     #Define a Submit button to submit the data -Submit = Submitfield (label='Register') -  -  -@app. Route ('/', methods=['GET','POST']) in defindex (): -  to     #instantiate a Form object +form =MyForm () -  the     #submit only if each field meets the criteria *     #Validate_on_submit (): There are two functions: $     #1. Verify that the field with the validators attribute is set to have data,Panax Notoginseng     #2. If there is data, verify that the form is set Csrf_token -     #print (Form.validate_on_submit ()) the     ifform.validate_on_submit (): +         #get the submitted data AName =Form.u_name.data thepasswd =Form.passwd.data +CONFIRM_PASSWD =Form.confirm_passwd.data -         Print(name, passwd, CONFIRM_PASSWD) $  $     returnRender_template ('wtf.html', form=form) -  -  the #launch this file using the Flask_script expansion pack - Wuyi  the if __name__=='__main__': -     #App.run (debug=true) WuManager.run ()

Third, database migration

1. Why Database Migration

In Flask-sqlalchemy, only the Db.create_all () and Db.drop_all () Two interfaces are provided, which is cumbersome to add or remove some fields, which is largely impossible to do with data in the table. Because using both interfaces causes the data in the table to be emptied. The migration of a database is essentially the operation of generating tables. And it is done without modifying the data in the table, just modifying the structure of the table without changing the data, such as adding or removing commands.

2. How to use the Flask-migrate expansion pack

In flask, you can use an expansion pack flask-migrate for database migration, which is used with the flask-script extension to improve efficiency.

To export the database Migration command, Flask-migarte provides a Migratecommand class that can be attached to the Flask-script Manager object.

Migrate = Migrate (app, DB)

Manager.add_command (' db ', Migratecommand)

3. Specific commands

Python database.py DB init: Create a migrations directory under the project directory with all migrated files inside

Python database.py db migrate-m "Init migration": automatically creates a migration script with upgrade () and downgrade (). -M Add a comment message

Python database.py DB Upgrade: Update database

Python database.py db History: Find the version number generated for each operation,

Python database.py db downgrade version number: Revert to the specified version

Iv. flask-session

In the flask framework, there is no integration to save the session information in the cookie information in the browser to the server, which is not very convenient. However, the Flask-session extension package provides the ability to synchronize session information to the server. In general, variable data such as session, Carousel, and so on are saved to the Redis database, because Redis has a very high performance. Next, you'll configure Redis in your project to save the session.

Add the following fields in the project configuration file:

  session_type: Indicates where the SESSION was saved. can have Redis,mongodb, Memcached,filesystem and so on, here choose to use Redis.

  Session_redis: Indicates a REDIS database object.

  Session_use_signer: Set whether to open the signature, that is, to further ensure security.

  permanent_session_lifetime: Set How long the SESSION is valid for. Generally set to 3-5 days.

Common expansion packs in the Python framework Learning flask

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.