当前位置:网站首页>P26-P34 third_ template
P26-P34 third_ template
2022-07-04 06:29:00 【Suyuoa】
The code is messy before you continue to use it , We will create a new project named third_template, There is still only one... In the project at this time main.py
Catalog
1.1.1 Use templates render_template()
1.1.2 Pass parameters to the template in the form of variable names
1.1.3 Pass parameters to the template in the form of a dictionary
1.4 Custom status code and response header
4.2 Catch error decorator errorhandler()
4.2.2 Decoration error message
1 Respond to
1.1 Back to template
1.1.1 Use templates render_template()
A template is a page file , The file format is html,js etc. , Let's create a folder first templates, Then create a new one called hello_world Of html file
- If you don't want to change the code, be sure to use templates
Enter the name, and after creation , Our document will have such content
We put Title Switch to hello world,body It says hello
Then we go back to main.py, Add a route and view
At this time, we turn on the service , And then visit
Find access to , And it's the same as what we entered
1.1.2 Pass parameters to the template in the form of variable names
We can also pass some information into the template , Let's modify the template
We can pass in the content in the form of two braces and variable name , Let's go back to main.py Define variables in
Let's visit
1.1.3 Pass parameters to the template in the form of a dictionary
So let's imagine django like that , Pass parameters in a dictionary , Then we should do so
- The variable name in our dictionary should be the same as that in the template
Let's visit
No problem found
1.2 Redirect redirect()
If I will Address a Redirect to Address b , So when I visit Address a I'll jump to Address b
If we input www.360buy.com This address , It will jump to www.jd.com This is redirection
Let's write one and see
After running, access 127.0.0.1/redirect, After visiting, the browser will pop up Baidu's page , stay pycharm Status code will be returned in 302
1.3 return JSON
Let's write about routing and views
After the visit, you can see our json data
1.4 Custom status code and response header
1.4.1 Custom status code
We can add the desired status code after the content to be returned , I currently set the status code to 888
Let's visit
1.4.2 Custom response header
The response header information is passed in the form of a dictionary , Add a dictionary after the status code
After visiting, let's look at the response header through the browser
I found that the dictionary we gave has been imported , If you only want to define the response header
If it's written backwards, it won't work , Will be submitted to the 500
The response header can pass multiple attributes through the dictionary
1.4.3 make_response The way
We can also customize the status code and response header in this way
- Here, the status code can only pass numbers
Let's visit
It is found that our customized status code and response header are in it
2 cookie
cookie Is the data stored on the user's local , It is generally used to identify users
2.1 Set up
We can go through make_response Medium set_cookie Set up cookie
Let's visit
We can see cookie The data of , We can also check here cookie
Here you can see us cookie Information about
Below the message will be cookie The validity of the , The default is when the browsing session ends , We will cookie It's called temporary cookie
We can go through max_age Parameters , To set up cookie The validity of the , We now set it to 3600 second ( An hour )
After the visit, let's take a look at cookie
We can find the settings by observing the response header cookie In fact, it adds... In the response header Set-Cookie This attribute
2.2 Read
Generally speaking, we use a route to send cookie Get out of here , Then go to another route to read cookie, Let's now write a view using request.cookies.get() read cookie
Let's now visit
Now we delete it in the browser
After deletion, let's visit
2.3 Delete
We can have this cookie What should I do when I go to school , Without this cookie Do another thing when you're young , So delete on the server side cookie It's also necessary
We use delete_cookie Delete cookie
After running, we first visit 127.0.0.1/set_cookie Set up a cookie
Then we'll visit 127.0.0.1/delete_cookie Delete one cookie
We found that Due time Given a singular value , We are now visiting 127.0.0.1/load_cookie to glance at
Find that the singular value actually represents cookie be without
- Set up cookie Is added in the response header Set-cookie This attribute , Delete cookie In fact, it is Set-cookie This property becomes null and the validity period will be given to a very early date , As shown above 50000 For many years, it has been a decoding problem
3 session
Let's start with session And cookie The difference between
- Storage location Theoretically session Stored in the server's cache ,cookie Store on client , however flask By default, the browser is used session, in other words session And cookie It's the same
- Object of action cookie It's for the website ,session It's for users , If I make a login interface , I like to ask users not to log in when they enter the login interface for the second time , Then I will put the user name and password data in session Not cookie in
What they have in common is that they return different pages according to different information , So below we see that the treatment is very similar
In the use of session front , We need to set it up first SECRET_KEY
3.1 Set up
Let's visit
We can see here session, The ciphertext here is in line with our previous settings SECRET_KEY Generated
You can also watch it here
3.2 obtain
Let's visit
4 exception handling
4.1 suspend abort()
Let's now write such a set of routes and views
Our normal visit should be like this
So if the user doesn't give age, Then it will report 500( Server error )
I don't want him to report now 500, I want him to report 400( Requester error ), We can use it at this time abort 了
Let's make another wrong visit
abort The actual utility of this is actually equivalent
4.2 Catch error decorator errorhandler()
4.2.1 Decoration status code
When our server reports a specified error , We don't want users to see such text
It's a fixed front-end content , This time we need to use errorhandler()
For example, when we appear 404 When , We can make him look better , We redirect it to an image in a static file
- The parameters of the view must be given , Whatever the name is , You can not call it , Its content is the wrong information
Now let's enter a random route to access
We didn't have this route , Should report 404, We decorated it , Final return to 200
If we were 500, So no matter which view you throw from 500 Error of , Will go to errorhandler View of this decorator
4.2.2 Decoration error message
If there is an error message, we can also decorate , For example, the divisor cannot be 0 Error of (ZeroDivisionError)
Let's start with a routing and view to make this kind of error , We'll take... Later num2 This variable is called 0 He made a mistake
Now let's make a decorator
Let's go through the normal interview first
Found nothing wrong , Let's put num2 Change it to 0
python There will be other mistakes , Input jupyter notebook Run in dir(__builtin__)) You can see all the errors that will occur , I am currently these
'ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError',
In addition to these, we can give custom errors , Here we need to use keywords raise, In my article, I introduce Python keyword _potato123232 The blog of -CSDN Blog
5 request hook
The request hook handles the preparation and finishing work during the interaction between the client and the server , Play the role of middleware ,flask There are four kinds of request hooks
The execution order of the running functions of the four hook bands is as follows
The way to create a hook is simple , What code should be hung on the hook after creation? Different processing should be done according to the different requirements of each project , Here we write down the way to create a hook
Let's use the division view above to measure , Deliberately divide by 0
At this time, I reported a 500, Let's look at the terminal information
except 500 Class has error information , There are no other error messages
边栏推荐
- Design and implementation of redis 7.0 multi part AOF
- Lightroom import picture gray / Black rectangular multi display
- Tree DP
- Json Web token - jwt vs. Traditional session login Authentication
- After the festival, a large number of people change careers. Is it still time to be 30? Listen to the experience of the past people
- 7. Agency mode
- Manually page the list (parameter list, current page, page size)
- buuctf-pwn write-ups (8)
- 746. Climb stairs with minimum cost
- JS arguments parameter usage and explanation
猜你喜欢
24 magicaccessorimpl can access the debugging of all methods
The solution of win11 taskbar right click without Task Manager - add win11 taskbar right click function
[March 3, 2019] MAC starts redis
Tree DP
Weekly summary (*63): about positive energy
JSON web token -- comparison between JWT and traditional session login authentication
Variables d'environnement personnalisées uniapp
4G wireless all network solar hydrological equipment power monitoring system bms110
ES6 模块化
JS how to convert seconds into hours, minutes and seconds display
随机推荐
双色球案例
[untitled]
2022.7.2-----leetcode. eight hundred and seventy-one
AWT common components, FileDialog file selection box
11. Dimitt's law
FRP intranet penetration, reverse proxy
How to avoid JVM memory leakage?
树形dp
Dimension and format of data
JS flattened array of number shape structure
Weekly summary (*63): about positive energy
JS arguments parameter usage and explanation
MySQL information_ Schema database
微信小程序使用rich-text中图片宽度超出问题
ABAP:OOALV实现增删改查功能
JSON web token -- comparison between JWT and traditional session login authentication
AWT introduction
Detectron:训练自己的数据集——将自己的数据格式转换成COCO格式
SQL join, left join, right join usage
2022.7.2-----leetcode.871