Flask Web Development The book is basically done, and the back needs to be studied, but the blog I do always feel a little bit humble, so in the brain to develop new features
Today think of the most basic function, custom avatar
That kind of function, designed to 2 basic function blocks
1: How to upload and save files
2: How to hook up the avatar photo with the user in the user model
The second question I consulted on the online discussion, came up with basically 2 ways
The first is to convert the picture into a binary and then into the database
The second is to store the image directly in the file system.
Upload Avatar, I feel for a long time, is to upload the file Bai Actually, there is a path, database storage this path, and then show to the front end, nothing to say, see how to achieve.
The database settings are as follows
User_image=db. Column (db. String (252), nullable=true)
Form form Design:
Avatar=filefield (' Avatar ')
Back-end implementation code
avatar=request.files[' Avatar ' fanme=avatar.filename upfile=os.getcwd () + ('/app/static/avatar/') ALLOWER_EXIT=[' Pang ', ' jpg ', ' jpeg ', ' jig ']flag= '. ' In Fanme and Fanme.split ('. ') [1] in Allower_exitif not flag: return render_template (' editperson.html ', form=form) Avatar.save (' {}{}{} '. Format ( UPFILE,USER.USERNAME,FANME)) user.user_image= '/static/avatar/{}{} '. Format (USER.USERNAME,FANME) Db.session.add ( User
The storage path is
/static/avatar/, support format pang, JPG, JPEG and other formats, this can be set according to their own needs. After the database stores a path after the last implementation of the database
Next is the front-end display
{% if username.user_image%}{%else%}{%endif%}
Here, the back end of the implementation of the uploaded Avatar code on Windows return error, said the file does not exist, I tried to modify, that is, the path name is not too long,
The path name is short, the error will be long. Windows development is a disadvantage, there is no problem with Ubuntu implementation