Flask_04
一、强制登录
@myblue.before_request
def xxx():
print("before requst")
print(request.path)
if "login" in request.path:
print("logining....")
return None
if not session.get("login"):
return redirect(url_for("xxxx"))
@app.before_request
def xxx():
print("before requst")
print(request.path)
if "login" in request.path:
print("logining....")
return None
if not session.get("login"):
return redirect(url_for("xxxx"))
二、文件上传
import os
class Config:
...
MEDIA_DIR=os.path.join(os.path.abspath(os.path.dirname(__file__)),"app/static/media")
<form action="{{ url_for('user.upup') }}" method="post" enctype="multipart/form-data">
<input type="text" name="username">
<input type="file" name="source">
<input type="submit" value="上传">
</form>
@myblue.route("/up/",methods=['post'])
def upup():
username = request.form.get("username")
file = request.files.get("source")
unique_name = str(uuid.uuid4())
ext = os.path.splitext(file.filename)[1]
uniquefilename = unique_name+ext
path="media/"+uniquefilename
user = User(name=username,pic=path)
db.session.add(user)
file.save(os.path.join(config.MEDIA_DIR, uniquefilename))
db.session.commit()
return render_template("xx.html",path=path)
<img src="{{url_for('static',filename=path)}}">
三、验证码
import random,string,os
@myblue.route("/cap/")
def getcaptcha():
from app.captcha.image import ImageCaptcha
image = ImageCaptcha(fonts=[os.path.abspath("xxx/segoesc.ttf")])
code = random.sample(string.ascii_lowercase+string.ascii_uppercase+string.digits,5)
session['code']=code
data = image.generate("".join(code))
response = make_response(data.getvalue())
response.headers['Content-Type'] = 'image/png'
return response