


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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 is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

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.

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.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
