Flask

虚拟环境的配置

pip install virtualenv 

创建一个虚拟环境,参数是虚拟环境的目标目录

virtualenv venv

激活虚拟环境

source venv/bin/activate

运行所需的依赖包

pip freeze > requirements.txt

 

1 开启调试模式,修改代码后不需要手动重启

1
2
app = Flask(__name__)
app.debug = True

2 路由中的变量

@app.route('/<name>', methods=['GET', 'POST'])
def home(name):
    return render_template('home.html',name=name)

3 关于配置文件

PASSWORD = '123456'

app = Flask(__name__)
app.debug = True
app.config.from_object(__name__)

print app.config['PASSWORD']

4 关于前端页面发送消息至后端

复制代码
  第一种: ajax
前端: $.post('/test',{ a:"data1", b:"data2" }, function(data,status){ alert("数据" + data + "状态" + status)
如果返回的json格式,则 JSON.parse(data).name })
后端:

a = request.form["a"]
b = request.form["b"]
print a + b
return "hello" 

也可以 返回 dit 

import json

from flask import, jsonify

c = {"name":"jinkang","sex":"man"}
return json.dumps(c)

 

第二种 就是 form 提交表单

<form action="/" method="post">

后端 request.form["name"] 获取 <input name="name" value="value">的值。

建议循环 request.form
for x,y in dic.iteritems():

x y 循环 表单中的 name 和 value 值。
复制代码

 错误页面的自定义

@app.errorhandler(404)
def not_find(error):
    return "404"

 一个 session 和 flash 消息的例子

复制代码
# -*- coding: utf-8 -*-

from flask import Flask, request, render_template, jsonify,redirect, url_for,session,escape,flash
import os,commands
import json
from werkzeug import secure_filename

app = Flask(__name__)
app.debug = True
app.secret_key = "adsfadfad"

@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template('home.html')


@app.route('/login', methods=['POST','GET'])
def login():
    username = request.form['username']
    password = request.form['password']
    if(username == "admin" and password == "123456"):
        session['username'] = username
        return redirect(url_for('homepage'))
    else:
        flash("the wrong username and password",'error');
        return render_template('home.html')


@app.route('/homepage', methods=['POST','GET'])
def homepage():
    if('username' in session):
        return "welcome" + session['username']
    else:
        return render_template('home.html')
    



@app.errorhandler(404)
def not_find(error):
    return "404"

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=3999)
复制代码

 关于模板继承

模板

<div>
<h1 style="color: red">THIS IS A TITLE</h1>
</div>
{% block content %}{% endblock %}

继承

{% extends "base.html" %}
{% block content %}
888888
{% endblock %}

 

关于 FLASK-RESTful 的一个例子

复制代码
from flask import Flask,request
from flask.ext import restful

app = Flask(__name__)
api = restful.Api(app)

class HelloWorld(restful.Resource):
    def get(self):
        return {'id': 'getmethod'}
    def post(self):
        val = request.form['key']
        print val
        return {'id': val}
api.add_resource(HelloWorld, '/hello')

if __name__ == '__main__':
    app.run(debug=True,port=3999)
复制代码

 

posted on   思此狂  阅读(176)  评论(0编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示