In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "how to build python miniWeb framework". In daily operation, I believe many people have doubts about how to build python miniWeb framework. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about "how to build python miniWeb framework". Next, please follow the editor to study!
Basic construction of miniWeb framework construction
Train of thought:
O determine whether the requested resource path ends with .py.
O if .py ends,-- > display dynamic content
O if .html ends,-- > display static content
Core code:
core code: # index.py if file_path.endswith (".py"): # 2. Let response_body = "This is index Show!% s"% time.ctime () # call the create_http_response function of the utils module and splice the response protocol response_data = utils.create_http_response ("200 OK", response_body.encode ()) # index.html else:. MiniWeb framework construction-dynamic display
Train of thought:
O must first be the file at the end of .py
O determine the requested resource path and set different response_body according to the resource path
O 404 error returned when the requested resource path does not exist
Core code:
# 3. Judge the requested resource path and display different amounts according to different paths: if file_path = "/ index.py": response_body = "This is index show!" # call the create_http_response function of the utils module Splicing response protocol response_data = utils.create_http_response ("200OK", response_body.encode ()) elif file_path = = "/ center.py": response_body = "This is center show!" # call the create_http_response function of the utils module Splicing response protocol response_data = utils.create_http_response ("200OK", response_body.encode ()) elif file_path = = "/ gettime.py": response_body = "helloworld!% s"% time.ctime () # call the create_http_response function of the utils module Response_data = utils.create_http_response ("200 OK", response_body.encode ()) else: response_body = "Sorry Page Not Found! 404" # call the create_http_response function of the utils module, and the splicing response protocol response_data = utils.create_http_response ("404 Not Found", response_body.encode ())
Implementation steps:
O create a urls module, the role of which provides a routing dictionary
The corresponding relationship between the dictionary saving path and the function
O import the module from application import funs of the function
Oroute_dict
Define the routing dictionary route_dict = {'/ index.py': funs.index,'/ center.py': funs.center,'/ gettime.py': funs.gettime}
Create a funs module that provides functions corresponding to specific functions
Define the function corresponding to the path
Import timedef index (): "" handle index.py requests "return" This is index showcases index.py funs "def center ():" handle index.py requests "return" This is center show! "def gettime ():" handle index.py requests "return" This is gettime show!% s "% time.ctime ()
Modify the judgment part of the dynamic display in the app file
1. Determine whether the path is in the routing dictionary key in dictionary
two。 If in the dictionary, take out the reference of the corresponding function according to the key (request path)
3. Execute the function, get the return value of the function, and then assign the value to response_body
If file_path in urls.route_dict: # according to the key value, go to urls.route_dict, get the value (function reference) func = urls.route_ path [file _ path] # according to the route dictionary, get the reference of the function, execute the function, and return the result of execution # Save to response_body variable response_body = func () # call the create_http_response function of the utils module, and splice the response protocol response_data = utils.create_http_response ("200 OK", response_body.encode ()) else: decorator routing (flask)
Use the decorator factory to implement decorator routing
Modify urls module
Route_dict = {}
Modify funs module
O Import from application import urls
O create a decorator factory and add the path to the dictionary (create a routing dictionary)
Def route (path): # parameters passed by path to the interior of the decorator path / index.py # decorator # dictionary # {"index.py": index function reference} def function_out (func): # func index function reference # 2-urls.route_ functions [path] = func # print ("decorate [% s]" % path) # decorator inner layer function def function_in (): # calls the original function and executes return func () return function_in return function_out
O decorating function
@ route ("/ center.py") def center (): "" process index.py request "" return "This is center show!"
O Import funs module in app module
The functions in the funs module are loaded and decorated at the same time (routing information is added to the dictionary)
Template replacement
Train of thought
O copy resources (templates) to the project
O modify the index and center functions in the funs module
O read the corresponding file in the function
List item
O replace the content in the web page with regular {% content%}-> helloworld!
O return the replaced content
With open ("templates/index.html") as file:? Content = file.read () return content database operation data load
Create and import data into the database
O create a database create database stock_db charset=utf8
O use database use stock_db
O Import database (login on client first)
O prepare script files
O Import script source stock_db.sql
Modify index function
O Connect to the database to get data
§Import module
§establish a connection
§create cursors
§execute sql using cursors
§get the results of the query
Data_from_mysql = str (cur.fetchall ())
§close resources
Close the cursor first, then close the connection
§replace with queried data
Content = re.sub ("{% content%}", data_from_mysql,content)
Render pa
Train of thought:
O traverse the query data and splice the text in html format
O represents a row, a column.
O replace with concatenated string
Content = re.sub ("{% content%}", data_from_myql,content)
O Note:
% s% s% s-> line # line is a tuple
Multi-table query
Train of thought:
O Association query
Select i.codeforme i.chg.turnover.price.highsPowerf.notebooks info from info i, focus f where i.id = f.id
O traverse the query data and splice the text in html format
O represents a row, a column.
O replace with concatenated string
Content = re.sub ("{% content%}", data_from_myql,content)
Multi-process version
Set up process daemon
P1.daemon = True
Start the process
P1.start ()
Close new_client_socket, otherwise the socket cannot be released
New_client_socket.close ()
At this point, the study on "how to build a python miniWeb framework" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.