


Detailed explanation of Web framework (Flask) in python (code example)
flask
flask是一个Python编写的Web 微框架,让我们可以使用Python语言快速实现一个网站或Web服务。
Using flask
When you write a function, if you want everyone to use it, you need to use flask to achieve this goal.
Import falsk.Flask class
Instantiate a Flask object
Bind routing
Run flask application
# 1. 导入Flask类; from flask import Flask # 2. 实例化一个Flask对象; # __name__是模块的名称或者包的名称 # 作用: 根据这个参数确定flask应用的路径, 从而快速查找模板和html文件的默认路径; # 模块就是python文件; 包就是目录(跟普通目录多加一个__init__.py); # app = Flask(__name__) # 3-1.基本路由:通过路由绑定一个视图函数 # @app.route('/'): 告诉Flask哪个URL才能出发对应的函数, 又称为路由; # 对应定义了一个视图函数, 也就是返回给用户浏览器显示的内容; @app.route('/') def index(): return "<h1 id="hello-world">hello world</h1>" @app.route('/login/') def login(): return "login" # 4. 运行Flask应用, 可以指定ip和端口; # '0.0.0.0' 所有的IP都可以访问到; app.run('0.0.0.0', 9000)
##Routing and variable rulesIn the flask framework, routing Represents the URL requested by the user and finds its corresponding processing function
Rules for common routing
- Part of the URL can be marked as a variable
- Common types of variables in routing in flask:
int, string, float, path, uuid
Copy after login
from flask import Flask, request app = Flask(__name__) @app.route('/<id>/comments/') def comment1(id): return "Comment id: %s" %(id) @app.route('/welcome/<user>/') def welcome(user): app.logger.debug('this is a debug') app.logger.warning('this is a warn') return user + "用户,欢迎来到SheenStar的主页" # 特殊的url地址: http://www.baidu.com/query?id=13&name=clotho @app.route('/query') def query(): # 获取url地址里面key值对应的value值; id = request.args.get('id') name = request.args.get('name') return "id: %s, name: %s" %(id, name) app.run()</user></id>
##Reverse URL
Get HTTP request data
Client passes URL When accessing the server program, two types of messages will be sent to the server, one is the HTTP request header, and the other is the request data.
1. 常见HTTP请求方法: GET: 1). 获取信息 2). 提交的信息会展示在url: http://www.wewtos.org/login?user=sheen&passwd=star POST:1). 提交信息, 不在url里面展示, 有利于数据的安全性; 2. 默认路由接受的请求方法为_____get____? 如何指定接收多个HTTP请求方法? 路由: @app.route('/login/', methods=['GET', 'POST']) 视图函数: def login(): 3. 如何判断用户请求的HTTP方法? request.method 如何获取用户POST请求提交的表单数据? request.form['user'] 4. 模板渲染(jinja2): why? python中生成html不易修改与维护, 所以将html的内容独立到templates目录中; how? 1). 去当前项目目录下寻找templtes是否存在?再去判断templates目录下是否有login.html文件? 2). 读取这个login.html文件的内容, 作为render_template的返回值; 3). 最终返回给用户浏览器; render_template('login.html') 5. 重定向和错误? redirect return render_template('login.html', message="用户名或者密码错误")
Example: Login jump
#这里的index.html、login.html、404.html是需要自己提前写好的可访问网页 #所有的模板需要放在templates目录下 from flask import Flask, request, render_template, redirect, url_for, abort app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'POST': print(request.form) # 1. 如何获取到用户提交的信息呢? user = request.form['user'] passwd = request.form['passwd'] # 2. 判断用户名和密码是否正确 if user == 'root' and passwd =='sheen': # 如果登陆成功, 跳转到主页; return redirect(url_for('index')) else: # 如果登陆失败, 重新登陆; return render_template('login.html', message="用户名或者密码错误") else: # 用户是GET请求, 返回登陆的html页面 # 1. 读取login.html文件的内容 # 2. 将读取的内容返回给用户界面 return render_template('login.html') # 404异常处理: 类似于捕获异常 @app.errorhandler(404) def not_found(e): return render_template('404.html') # 抛出异常 @app.route('/user/<user_id>/') def user(user_id): if 0<int app.run><h1></h1> <p style="text-align: center;"><span class="img-wrap"><img src="/static/imghw/default1.png" data-src="https://img.php.cn//upload/image/438/648/136/1540373077718507.png" class="lazy" title="1540373077718507.png" alt="Detailed explanation of Web framework (Flask) in python (code example)"><br></span></p> <p style="text-align: center;"><img src="/static/imghw/default1.png" data-src="https://img.php.cn//upload/image/410/199/933/1540373095508604.png" class="lazy" title="1540373095508604.png" alt="Detailed explanation of Web framework (Flask) in python (code example)"><span class="img-wrap"> </span>##</p></int></user_id>
The above is the detailed content of Detailed explanation of Web framework (Flask) in python (code example). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
