Flask 路由和URL传参数

控制器文件IndexController.py

from flask import Flask;

app = Flask(__name__);
# 不区分URL最后的斜杠
app.strict_slashes = False;

@app.route('/flask')
def hello_flask():
   return 'Hello Flask';

@app.route('/python/')
def hello_python():
    return 'Hello Python';

# URL传参
# 参数格式:<type:variableName>, type默认为string
@app.route('/blog/<int:postID>')
def show_blog(postID):
    return 'Blog Number %d' % postID;

if __name__ == '__main__':
    app.run('0.0.0.0', 8080, debug = True);

运行

$ python IndexController.py
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 158-818-550
 * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)

使用浏览器访问

http://localhost:8080/flask
http://localhost:8080/python
http://localhost:8080/python/

http://127.0.0.1:8080/blog/11

使用curl访问

$ curl http://localhost:8080/flask
$ curl http://127.0.0.1:8080/blog/11

参考:
https://www.tutorialspoint.com/flask/flask_variable_rules.htm

相关文章
简单应用- Hello world

您的代码已经是一个良好的起点,但有一些可以进行优化的地方。下面是对您提供的代码进行优化的建议: 1. 使用密码哈希:在据库中存储密码的哈希值而不是明文密码,可以提高安全性。 2. 使用表单验证:在服务器端进行用户名和密码的验证,而不是直接执行SQL查询。 3. 使用`flash`消息:使用`flash`消息来向用户显示错误信息,而不是将错误信息作为参传递给模板。 4. 重命名路由:将路由的名称更改为更具描述性和一致性的名称。 下面是优化后的代码示例: ```python from flask import Flask, render_template, request, redirect, url_for, session, flash from werkzeug.security import check_password_hash app = Flask(__name__) app.secret_key = 'your_secret_key' @app.route('/') def home(): if 'username' not in session: return redirect(url_for('login')) else: return redirect(url_for('index')) @app.route('/index') def index(): return render_template('index.html') @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form.get('username') password = request.form.get('password') # 查询据库检查用户名和密码是否匹配 query = "SELECT * FROM users WHERE username=%s" values = (username,) cursor.execute(query, values) user = cursor.fetchone() if user and check_password_hash(user['password'], password): session['username'] = user['username'] flash('登录成功', 'success') return redirect(url_for('index')) else: flash('用户名或密码错误', 'error') return redirect(url_for('login')) else: return render_template('login.html') if __name__ == '__main__': app.run() ``` 注意,上述代码假设您已经在据库中存储了用户的密码哈希值,并且已经配置了据库连接。请根据您的实际情况进行相应的修改。此外,还需要根据您的实际需求来调整`index.html`和`login.html`模板文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值