当前位置:网站首页>About the log traffic monitoring and early warning small project | standardized return of interaction with the database in flask
About the log traffic monitoring and early warning small project | standardized return of interaction with the database in flask
2022-06-11 00:57:00 【Smelly Nian】
stay flask It interacts with the database :
Use orm Manipulate the database (orm Or at the bottom pymysql)
orm: object relational mapping( Object relation mapping )
flask Unnecessary and complex sql Deal with sentences It's just manipulation orm Objects will do
orm It is used to map the table structure in the database into model classes
The object generated by the class is each row of records in the database

The configuration file setting Add database configuration :
first line : Connect to database
SQLALCHEMY_DATABASE_URI = user name : password @ Database host / database ? Character set

After that model Create a new __init__.py
Create a db object Try to make db and app Binding And import the table to run

dependent user.py
It is equivalent to creating a new user surface If the set field is specified as String type You need to specify the length
User Every other class Is a model It must inherit db.Model class
A class is mapped to a table in the database
Class will instantiate And every object instantiated It is a row of records in the table

user.py Inside : New users

Then bind the blueprint to app above

Use dynamic url Implementation delete
User.query.get() Use get lookup , Primary key only get You can only get To the first Therefore, only a single operation


Change : Just the same, only one item can be modified


check :


Type in the browser url What happens to the request ?

Client initiates request
The server receives the request analysis http baotou ( The header field of the package has url And the request method ) Get body data
adopt url And request methods to perform judgment processing
- adopt url Come on url_map Find the corresponding... In the table endpoint
view_function Find the corresponding view function in the table
- Judge whether the request method is correct
Call the corresponding view function for processing
It can be done by request Object to get the passed in parameters
You can also use dynamic url Get the parameters
If there is database operation Import the corresponding model class
Here by manipulating orm Object to manipulate the database , Add, delete, modify and query the database
For query operations , Database objects cannot be returned directly , It needs to be serialized
Corresponding format conversion is required , It is recommended to use json
Return to the corresponding api data
The serialization operation can be directly placed in user.py In the class of

So we don't need to return here manually

Put a single query and all queries in one function

When manipulating the database, you must remember to submit

The project needs to be standardized :
Return to json Format
Need to return the status code (status): Define the logical state of the program
also message Explain the meaning of the status code
data Data returned by request Put all the data in data Inside
General format :{“status”:10000,“message”:“ Data request successful !”,“data”:[]}
So take this as a public setting Define a new folder libs( Store public functions )
And then create a utils( It holds all the tools )
![]()

In this way, standardization can be achieved Normalization
Start project :
- project Set up a project team Divide responsibilities
- Demand collection Demand analysis
- Design this project Product prototype Database design , Interface design (url The ginseng )
- Write code
- Test online
Flask Provide the interface You can add monitoring items Monitoring items can also be displayed


Because we don't have a front end now So we will show the operation later Can only be completed through the interface
For ordinary users , Only you can see the monitoring items you add
For Administrators , All the monitors can see
For the project user when It is recommended that the user password be hashed For roles, it is recommended to set them to enumeration type
monitor What is stored inside is a monitoring table
Establish relationships between tables ( Be sure to set foreign keys )
stay model Of user.py Inside with monitor Table create connection
![]()
![]()
On the command line Help manage flask Tools for :flask-scrip
Once installed We give up server.py I've created a new one manage.py
Now our main program The core object It's all in the hands of manage.py 了
Now? python manage.py It is equivalent to an order Parameters can also be connected But it is also started by default
So we need to use the command line to specify the port Path, etc
Start the program from the command line :python manage.py runserver -h 192.168.0.25 -p 8000
python manage.py There are three parameters
db
runserver: start-up
shell: Run one python Of shell Program
![]()
Equivalent to entering app Internal
Everything manipulated here is manipulated app


So there is one more object in the monitor attribute monitor Attribute contains user Of id( because id Is set to a foreign key ) Same monitoring items ( That is to say monitor Data in table )
User pass monitor Property to find the monitor
monitor The table adds a reverse query user moniter The object of can pass through user Property to find the user

This relationship is not database yes orm Of There is no need to query the table

hold api More standardized :flask-restful( Is a style of software application )( Interviews often test )
restful:
#REST(representational state transfer)(api Design method of ): Presentation layer state transition
It's not necessary It is just a general software design style
Generally speaking, it's Resources in the network in some form of state transition
resource: resources That's data For example, user data is a kind of resource Monitoring data is a kind of resource
representational: Some form of expression Such as JSON,html
state tranfer: State shift . adopt http Method realization ( In fact, it is equivalent to adding, deleting, modifying and checking users Use http The verb of This is a rest Rules of use )
Such as Not used rest : Used rest that url Just two or one
( Different ways to do different things )
/user It is a kind of resource /user /user/id
/user/add post Method
/user/delete delete Method
/user/update update Method
/user/get get Method
Divide by resources url, There is no need to divide it according to the action
Each type of resource is given to one or two url adopt http Different methods are used to add, delete, modify and query such resources
accord with rest The structure of the principle We call it restful framework
This also carries the version number Specifies the api How to design The corresponding format is specified The status code is specified
every last url It represents a kind of resource
Client through four http Method to operate on server resources
such as For resources such as users (id yes user The database of id)
GET /v1/user Get all users
GET /v1/user/id Get a user (v1 It's the version number 2 representative id)
POST /v1/user New users
PUT /v1/user/id New users
DELETE /v1/user/id Delete user

Now you can go through server.py To run You can also run from the command line
about python call Linux command Recommended subprocess
Inquiry is the easiest test !!!!!
Query by criteria :
Precise query filter_by Fuzzy query filter
Filter_by No, filter flexible
![]()
![]()


Multiple conditions :

Sort :

Limit :

Query summary :
Query summary :
1.User.query.all() all
2.User.query.get(pk) One
3.User.query.filter()
If the field to retrieve is a string (varchar,db.String)
User.username.startwith('')
User.username.endwitd('')
User.username.contains('')
User.username.like('') The passed in parameter needs to be added %
User.username.in_(['','','',''])
User.username==
If the field to be retrieved is an integer or date type :
User.age.__lt__(18) Double underline
User.rdatetime.__gt__('.....')
User.age.__le__(18)
User.age.__ge__(18)
User.age.between(18,25)
Multiple conditions are retrieved together :and_ or_
Necessary condition :or_
Sort :order_by()
Get the specified quantity :limit() offset()
4.User.query.filter_by(username='xxx') User.query.filter(username== 'xxx')
Delete
Two kinds of deletion :
1. Logical deletion , It's just an update ( When defining tables in a database , Add a field named isdelete, This field controls whether to delete )
id=request.args.get(id) Used to receive get Parameters in the request
user=User.query.get(id)
user.isdelete=True
db.session.commit()
2. Physical delete ( Completely remove from database )
id=request.args.get(id) Used to receive get Parameters in the request , if post Just put args Replace with form
user=User.query.get(id)
db.session.delete(user)
db.session.commit()
3. to update
id=request.args.get(id)
user=User.query.get(id)
# Modify the properties of an object
user.username=xxx
user.phone=xxx
# Commit changes
db.session.commit()
Need to submit :
add to
user=User()
user.xxx=xxx
db.session.add(user)
db.session.commit()
Delete
user=User.query.get(id)
db.session.delete(user)
db.session.commit()
to update
user=User.query.get(id) # Get the objects in the database
# Modify the properties of an object
user.username=xxx
user.phone=xxx
# Commit changes
db.session.commit()
Standardized return :
Our project usually prepares a description document ( You can directly extract part of the project document and put it into the description document ), It is important to organize the documentation ( Documentation is for others to use )
The request parameter is url The variable passed in after the value passing question mark
The returned parameters indicate what we are returning
The transmission on the network is usually in the form of string and json Format is to easily convert the string format to the desired object Norms are conventions that return json Format
http The status code only focuses on whether the request is successfully connected to get data Instead of focusing on whether the data we get is what we need So each of our applications will have its own status code
( Then you can describe the information message To see what kind of failure we are )
边栏推荐
- Alicloud configures SLB (load balancing) instances
- lucene思维导图,让搜索引擎不再难懂
- [no title] 66666
- Optimization of startup under SYSTEMd, deleting useless SYSTEMd services
- With a market value of 21.5 billion yuan, will the post-80s generation in Sichuan make TV history?
- The JVM determines whether an object can be recycled
- Complete collection of MySQL exercises (with answers) - you will know everything after practice
- Objects as points personal summary
- 负载均衡策略图文详解
- Learning notes: hook point of plug-in activity
猜你喜欢

Introduction and basic construction of kubernetes

Wechat applet to realize OCR scanning recognition

如何在office2016(word2016)中安装mathtype6.9及相关问题解决方案

About log traffic monitoring and early warning small project | flask
![[network planning] 2.2.4 Web cache / proxy server](/img/a8/74a1b44ce4d8b0b1a85043a091a91d.jpg)
[network planning] 2.2.4 Web cache / proxy server

Review of software architecture in Harbin Institute of technology -- LSP principle, covariance and inversion

Pirate OJ 448 luck draw

UUID quick explanation

Load balancing strategy graphic explanation
![[论文阅读] BoostMIS: Boosting Medical Image Semi-supervised Learning with Adaptive Pseudo Labeling](/img/10/a60cfe830e2238de00121d7bd95ad6.png)
[论文阅读] BoostMIS: Boosting Medical Image Semi-supervised Learning with Adaptive Pseudo Labeling
随机推荐
STM32下载代码后出现无法再次下载的问题
[论文阅读] BoostMIS: Boosting Medical Image Semi-supervised Learning with Adaptive Pseudo Labeling
Adapter mode
Logback log framework
LeetCode 8. 字符串转换整数 (atoi)(中等、字符串)
BGP basic concept and iBGP basic configuration
[network planning] 2.1.2 transport layer services that can be selected by the application
Synchronized keyword for concurrent programming
UUID quick explanation
网络工程师必修课防火墙安全区域及安全策略基础操作
Dual wing layout
LeetCode 8. String to integer (ATOI) (medium, string)
[network planning] 3.2 transport layer - UDP: connectionless service
为什么使用 Golang 进行 Web 开发
systemd 下开机启动的优化,删除无用的systemd服务
中小企业数字化转型为什么这么难?
lucene思维导图,让搜索引擎不再难懂
MySQL
B 树的简单认识
Can I buy annuity insurance? Is annuity insurance safe?