Moment For Technology

Flask Usage details ⚡ Basics | Python theme month

Posted on Dec. 3, 2022, 8:41 a.m. by Arnav Mane
Category: The back-end Tag: The back-end

This article is participating in Python Theme Month. See the link to the event for more details


Then today in preparation for the summer program, has recently been doing so our project is the end of the python class start with python, like Java's classmate also don't get discouraged, behind will be appropriate to write a Java class students like a wave, can focus on the summer vacation with knock, can also collect a wave first when free to try, Ok, let's get into the business, shout the exit "== not fat body, fat knowledge =="

Emphasize: the content of the article do not understand or have a problem can leave a message oh, in addition to say that I this is just a basic introduction suggest you or look at the end of my article sent resources can be understood in detail.

Why flask

The FLask framework itself only implements the most basic functions, so FLask is called a microFramework, and in terms of the amount of code, it is. But from an engineering point of view, this so-called "small", but brings more convenience. Flask is much more convenient than Django for large projects. Large means that you need to customize the Admin system (such as layers of administrators, each administrator can customize admin groups), complex database operations, many, many forms across entity operations, validation, etc.

The rich third-party library resources make it easy for you to write almost any type of program. FLask-SQLAlchemy for database operation, FLask- WTF for form verification, FLask-Login for management, FLask- Mail for Mail... So Flask has one more thing that's obvious when compared to its cousin Django: flexibility. You can choose any third-party extension you like

Install the flask

pip install flask
Copy the code

But this installation is a little slow, or suggest switching to Tsinghua source, or douban source these mirror

pip install flask -i 
Copy the code

Another thing to mention is that it's better to build projects when you're writing projects == use virtual environments == this will prevent some python package conflicts, and for those of you who are not good at creating virtual environments I recommend a book below with a detailed tutorial.

Start the flask

from flask import Flask

app=Flask(__name__)# Create an instance so that there is a special section for this

@app.route('/') #.route creates a route from the instance and tells Flask what URL will trigger our function
def hello() : Simply create a function
    return 'hello'

if __name__=='__main__': is what flask starts with, and it has many parameters in it. It is recommended to use debug=True. The built-in debugging is always better than your own' instead,port=3308)This is for specific host and port, depending on whether your default port is used
Copy the code

See the debugger operation for details:portal

What is a name for in a flask

Flask has a name in it. This is for launching the flask template. If you are using a single module (as shown above), you should use the name. The name of the module will vary depending on whether it was started as a separate application or imported as a module (that is, 'main' or the actual import name). This is a must, so Flask knows where to find templates, static files, etc., plus:

Static_folder: indicates the static folder. The default value is static folderCopy the code
Static_url_path: indicates the static web page addressCopy the code
Template_folder: Templates folder by defaultCopy the code

It doesn't matter if you don't understand a little bit here, but the book will give you a detailed explanation so you can develop the project yourself. You can also look at the official document portal first

Converter and variable rules

To add a variable section to the URL, you can mark these special fields as , and this section will be passed to your function as a named argument. The rule can use Converter :variable_name to specify an optional converter. The converter mainly uses the value at the end of the page as a standard to get to another page. We often see encrypted strings that do this

from flask import Flask
app = Flask(__name__)
@app.route('/user/username')# Define the converter
def show_user_profile(username) :# Pass the converter into the function
    # show the user profile for that user
    return 'User %s' % username
def show_post(post_id) :
    # show the post with the given id, the id is an integer
    return 'Post %d' % post_id
if __name__ == '__main__':
Copy the code
Flask default converters: DEFAULT_CONVERTERS = {' default ': UnicodeConverter,' string ': UnicodeConverter,'any': AnyConverter,' path ': PathConverter,'int': IntegerConverter,'float': samplecomposite,' uuid: UUIDConverter,}Copy the code

Here's how you define the converter

class rc(BaseConverter) :      
 Override the properties of the parent class to define the converter rules
    def __init__(self,url_map) :
        # Verify the regular expression of QQ mailbox
        self.regex ='[0-9 a - zA - Z_] {0} 3 @'
    # Define the return value under the view function
    def to_python(self,value) :
        return val
    def to_url(self,value) :# returns url
        return value
app.url_map.converters['em'] = rc # Add custom converters to the converters list
@app.route('/emm/em:email') # Add a new converter
def email(email) :
    return 'email is:%s' % email # return email
Copy the code


Redirection is also important in Web development. It can be used to jump from one web page to another, which is equivalent to the operation after refreshing. For Flask, it mainly involves two modules (redirect, url_for)

@app.route('/ 1')
def fg() :
    return '1122'
Copy the code

from flask import redirect,url_for
def refer() :
    return redirect('/ 1')# Create another route
Copy the code

This will jump directly to the function in the route (' /1 ') and display the return value. We can access the routing function and then jump to the corresponding content page. This is called indirect jumping

def ref() :
    return redirect(url_for('fg')) This direct access to the ref child page can directly jump to the corresponding page
Copy the code

Setting the error page

Flask has two methods: one is to use the system abort to directly assign a value, and the other is to use the custom errorHandler function

  • useAbort ()You can useredirect()The function redirects the user to another location. Discard the request and return the error code withabort()Function. Here's an example of how they can be used:
from flask import abort, redirect, url_for
def index() :
    return redirect(url_for('login'))
def login() :
    abort(401)#401 means no access
Copy the code
  • By default, error codes are displayed with a black and white error page. If you want to customize the error page, you can use the errorHandler () decorator:
from flask import render_template
def page_not_found(error) :
    return render_template('page_not_found.html'), 404
Copy the code

Notice the 404 after the render_template() call. This tells Flask that the error code for this page is 404, which means it was not found. The default is 200, which means everything is fine.

Json data reading

Json as a general data transmission format is relatively practical, flask as a Web framework for it of course also has some processing power, currently using Jsonify

def json1() :
    return jsonify(data)

def json2() :
    return jsonify(hour=12,second=21)
Copy the code

The cookie and session

What's held in a session is the session content, it's in a cookie, and it allows us to directly log into some system that we've already logged into. So in order to manipulate a session we need to introduce a session module that's dedicated to it, and we need to configure a security key in order to use a session so let's talk about the cookie

Cookie set_cookie(key, value=' ', max_age=None, expires=None,path='/', domain=None, secure=False, httponly=False,samesite=None) key: key value: value Max_age: Sets the expiration time (seconds) Expires: sets the expiration time.1970Path: indicates the current primary domain name. Domain: indicates the subdomain nameCopy the code
Set cookie and headers
def set_cookie() :
    response=make_response('Cookie set successfully')
    # Cookie is valid for 30 days cookie validity period
    response.set_cookie('user'.'admin',expires=time) # Set cookie for user name
    response.set_cookie('pass'.'123456',expires=time) # Set password cookie
    response.headers['X-Something'] ='mything' Chinese is not allowed here
    response.headers['Server'] ='feixue' # Server name
    return response
Copy the code

The acquisition and deletion of cookies

The request module is not a crawler's requests

def get_cookie() :
    name="Username :"+request.cookies.get('user') +"Password:"+request.cookies.get('pass')
    return name
Copy the code

There are two ways to delete cookies. 1. Setting The cookie expiration time to 0

def del_cookie1() :
    response=make_response('delete cookie 1')
    response.set_cookie('user'.' ',expires=0)
    response.set_cookie('pass'.' ',expires=0)
    return response
Copy the code

2. Delete cookies directly

def del_cookie2() :
    response=make_response('delete cookie 2')
    return response
Copy the code

One thing to note about using cookie-based sessions: Flask serializes the values you put in the session object to Cookies. If you find that some values do not persist between requests, and you do have Cookies enabled, you do not get a clear error message. At this point, check the size of Cookies in your page response and compare it to the size supported by your Web browser.

The session operation

The problem with setting up a session and configuring random security keys is that it's hard to tell what's really random. A key should be random enough. Your operating system can generate nice random values based on a key random generator that can be used as a key:

Copy the code

Set session dictionary

session['user'] ='fei'
session['pass'] ='xue'
Copy the code

Example Set the session expiration mode

session.parmanent=True Expires after 31 days by default
# Session expires in two hours
app.config['PERMANENT_SESSION_LIFETIME']= timedelta(hour=2)
Copy the code

So it's going to be

def session1() :
    session['user'] ='fei'
    session['pass'] ='xue'
    session.parmanent=True Expires after 31 days by default
    return 'login success'
Copy the code

Get session get () get and index get. Index get is not stable, but get is recommended

def session2() :
    return 'hello %s %s'%(us,pa)
Copy the code

Delete sessions one by one

def session3() :
    return 'delete successful! '
Copy the code

Delete all

def session4() :
    return 'delete successful! '
Copy the code

The use of the request

So we're going to talk a little bit about the use of request, which is a module that's designed to manipulate web requests. Request Indicates the GET request

You can specify the request mode by setting its methods parameter.@app.route('/get', methods = ['GET'.'POST'])
def get() :
    if request.method == 'GET':
        return 'This is a GET request.'
        return 'This is another request.'
Copy the code

A post request

@app.route('/post', methods = ['POST'.'GET'])
def post() :
    if request.method == 'POST':
        return 'This is a POST request'
        return 'This is another request.'
Copy the code

The request of the args

Records of the query parameter in a get request, generally used to query, search your name
Copy the code
It returns the parameters in the GET request, such as the url above, which is: searchType=songsearchKeyWord= your nameCopy the code
Request. Args [request.'keyword']
Copy the code

The form of request records the form data in a request and is typically used for form submission. For example, when we register for a website, we often need to submit forms.

We can get the content of the form by using: request.form['keyword']
Copy the code

The request of the headers

Return request page header information, return a list. request.headers['keyword']
Copy the code

Blueprint Development essential

This program is stored in a file called

from flask import Flask
def df() :
    return 'hello world'
def lk() :
    return 'efhsfj'
Copy the code

So there will be

from flask import Flask,request
from fei import *
def login() :
    return request.url
if __name__ == '__main__':
Copy the code

The essence of calling a functional blueprint from a main file is to introduce multiple modules into one main module, which is equivalent to writing the module ourselves and using it as a blueprint for calling. The blueprint view function can be used to distinguish the same method among multiple blueprints.


Views can be understood by everyone in view of the same meaning, such as the mysql database view, the truth is all interconnected, not too much difference, just different function. The way to create views is also simple, inherited from flask's views class. The view of a class

from flask.views import View
def ff() :
    return 'ok'
class st(View) :
    def dispatch_request(self) : # Must implement this method
        return "Wayward '90s boy"
# Class views are mapped to urls using the add_URl_rule method
Copy the code


from flask.views import MethodView
def gg() :
    return 'ok'
class login(MethodView) :
    Function that is executed when the client accesses it via the get method
    def get(self) :
        return 'get'
    Function that is executed when the client accesses via the POST method
    def post(self) :
        email = request.form.get("user")
        password = request.form.get("pass")
        if user== 'gffsadff' and pass= ='4fsaferwf':
            return "Login successful"
            return "Login failed"

Add_url_rule adds a mapping between the class view and the URL, and specifies the name of the URL in the AS_view method to facilitate url_for function calls

Copy the code

Resource sharing

Flask Web development is based on Python. If you want to learn flask Web development in Python, you can find the flask resources on my homepage. Of course, you can also send me personal messages. Finally, I would like to share with you my favorite pictures recently. Welcome your support

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.