routing

When you set up urls for Web applications, you need to set meaningful urls to help users remember them. For example, the LOGIN URL can be set to /login and the logout URL can be set to /logout. Rather than setting up a bunch of meaningless strings that would just disgust the user.

Use the Route decorator to bind functionality to the URL.

@app.route('/')
def index() :
    return 'Index Page'

@app.route('/hello')
def hello() :
    return 'Hello, World'
Copy the code

You can also do more, making partial urls dynamic and attaching multiple rules to a function.

One other thing you need to know is routing functions and decorators

from flask import Flask

Route function add_url_rule and decorator
app = Flask(__name__)

@app.route('/')
def hello() :
	return 'Hello world'

def index() :
	return 'hello everyone'

app.add_url_rule('/index', view_func=index)

if __name__ == '__main__':
	app.run()
Copy the code

The add_url_rule function tells the server where we want to go, and the server jumps to the specified page.

Variable rules

We can tag parts with variables, add dynamic parts to the URL, and tag them with <>(a pair of Angle brackets).

from flask import Flask
import settings

app = Flask(__name__)
app.config.from_object(settings)

data = {'a':'Beijing'.'b':'Shanghai'.'c':'guangzhou'.'d':'shenzhen'}

@app.route('/getcity/<key>')
def getcity(key) :
	return data.get(key, 'Lost')
	
@app.route('/add/<int:num>')
def add(num) :
	result = str(num + 10)
	return result

@app.route('/path/<path:subpath>')
def get_path(subpath) :
	return subpath

@app.route('/uuid/<uuid:my_uuid>')
def get_uuid(my_uuid) :
    return F 'yields uUID:{my_uuid}'


if __name__=='__main__':
	app.run()
Copy the code

Except for strings, which default to STR, all other integers, floating points, and so on require the flags int and float.

Note that the value returned can only be a string.

path

In the code above you can see that there is a tag of type PATH. So when do you need it?

When the following path is dynamically changing, we can get the changing URL in this way.

uuid

Uuid is an abbreviation for a universal unique identifier and is a standard for software construction, in which case you don’t need to worry about duplicate names when creating databases.

The uuid is a 128bit value that can be calculated using a certain algorithm. Uuid is used to identify the attribute type and is treated as a unique identifier in all space and time.

The common format of a UUID is XXXXXXXX-XXXX-XXXX-XXXXXXXX (8-4-4-12).

In the meantime, we can use Python to generate data in UUID format

import uuid

uid = uuid.uuid4()
print(uid)
Copy the code

Note: If the correct UUID format is not written, the URL will be blank when accessed.

With the exception of string and numeric data, other data types are used sparingly.

The importance of /

# The difference between the following two rules is whether a trailing slash is used


from flask import Flask
import settings


app = Flask(__name__)
app.config.from_object(settings)


@app.route('/project/')
def projects() :
	return 'The project page'


@app.route('/about')
def about() :
	return 'The about page'

if __name__ == '__main__':
	app.run()
Copy the code

There are two paths in the above code, the first is /project/ and the second is /about.

The first path has a trailing slash, while the second path has no trailing slash.

When I visit:

http://localhost:5000/project/
Copy the code

You should know that The value returned is The Project Page

When I visited:

http://localhost:5000/project
Copy the code

It will jump to the page and then visit again

http://localhost:5000/project/
Copy the code

The project URL is regular, with a trailing slash that looks like a folder. Flask automatically redirects when accessing the end of a URL without a slash and adds a trailing slash.

The about URL does not have a trailing slash, so it behaves like a file, and if you access the URL you get a 404 error by adding a slash. This keeps the URL unique and helps search engines avoid indexing the same page twice.

The Response object

Returns a normal string

The flask view function returns a string without converting it

app = Flask(__name__)
@app.route('/')
def index() :
    return 'Hello World'
Copy the code

In fact, the above return is converted to Response by default, which is the same as the following code.

from flask import Flask, Response

app = Flask(__name__)
@app.route('/')
def index() :
    return Response('Hello World')
Copy the code

The json data

If you want to return lists, dictionaries, etc., you need to return json data first.

from flask import Flask, jsonify

app = Flask(__name__)
@app.route('/')
def index() :
    dict_data = {
        'name': 'Book-learning'.'age': 20
    }
    return jsonify(dict_data)
Copy the code

Return a tuple

It is required to return a tuple containing three parameters: response, status_code, or headers.

from flask import Flask
import json

app = Flask(__name__)
@app.route('/')
def user() :
    json_dict = {
        'name': 'Book-learning'.'user_info': {'age': 20}
    }
    data = json.dumps(json_data)
    return data, 200, {"ContentType":"application/json"}
Copy the code

Headers is not written here, and the system has a default response header.

Gets basic information about the object

from flask import Flask, Response
import settings


app = Flask(__name__)
app.config.from_object(settings)

@app.route('/index')
def index() :
	response = Response('

Hi, what's for lunch today

'
) print(response.content_type) print(response.headers) print(response.status_code) print(response.status) return response if __name__=='__main__': app.run() Copy the code

For more basic information and operations, check flask’s website.

The last

Biting books says:

Every word of the article is my heart to knock out, only hope to live up to every attention to my people.

Click **[see] and [like] **, let me know that you are also working hard for their own learning and efforts.

The way ahead is so long without ending, yet high and low I’ll search with my will unbending.

I am book-learning, a person who concentrates on learning. The more you know, the more you don’t know. See you next time for more exciting content!