A tutorial on implementing the profile and avatar of a logged-on user in the flask framework of Python _python

Source: Internet
Author: User
Tags datetime time zones md5 time and date

User Profile page

On the User profile page, there is basically nothing special to emphasize and introduce the new concept. You just need to create a new View function template page that contains HTML.

The following are the view functions (project directory/views.py):

@app. Route ('/user/<nickname> ')
@login_required
def user (nickname):
  user = User.query.filter_by ( Nickname = nickname). (a)
  if user = = None:
    Flash (' No users: ' + nickname + '!) ') return
    redirect (url_for (' index '))
  posts = [
    {' Author ': User, ' body ': ' Test post #1 '},
    {' Author ': US Er, ' body ': ' Test post #2 '}
  ] return
  render_template (' user.html ',
    user = user,
    posts = posts)

The @app.route logo is mainly used to illustrate that this view function is different from those before. We have defined a parameter named <nickname>. Within a function it will be converted to an argument with the same name, and when the user has a request, such as a url:url/user/miguel, the secondary view function is recognized as having an argument named nickname value of ' Miguel ', that is, nickname = ' Miguel '.


There is no need to be surprised by the way the process is implemented. First we need to try to call the user's data from the database by using the transformed nickname parameter as a condition. If there is no query to the data, we will, as before, give the user a false hint and jump to the homepage.

Once we've found the user, we'll show the user's article under the template. Note that in the User profile page we only allow the user to display the article, so the author of the article is the user.

The initialized view template is very simple (project directory/templates/user.html):

<!--extend Base layout-->
{% extends ' base.html '%}
 
{% block content%}
 
 

The User Information page is done, but there is no link address to change the page in the site. To make it easy for users to view their own information, we put the link address to the top navigation (project directory/templates/base.html):



<div>microblog:
    <a href= ' {{url_for (' index ')} ' >Home</a>
    {% if g.user.is_authenticated () %}
    | <a href= "{{url_for (' user ', nickname = G.user.nickname)}}" > Your profile </a>
    | <a href= "{{url_for (' Logout ')}} " > Exit login </a>
    {% endif%}
  </div>

Notice the URL that we have given to the function after we have passed it.

Let's try this project now. Clicking on the "Your profile" link above will jump to the user profile page. Since we have not yet pointed to a random user information page of the link address, so here if you want to see other people's data, you need to manually enter the address. For example, if you want to read Miguel, the address is: Http://localhost:5000/user/miguelt


Avatar Section

I'm sure you'll find that the current user profile page looks monotonous. In order to look good, we will add the user avatar function.

In order to avoid our server needs to deal with a large number of uploaded images, we are here to use Gravatar to provide the user avatar can be.

Since returning a user avatar belongs to the user, we put the code inside the Theuserclass (project directory/models.py):


From hashlib import MD5
#
... Class User (db. Model):
  #
  ... def avatar (self, size): Return
    ' http://www.gravatar.com/avatar/' + MD5 (self.email). Hexdigest () +
    '?d=mm& s= ' + str (size)

Avatar will return the address of the user avatar image and request the pixel size of the picture you want according to your needs.


It's easy to get image pictures from Gravatar. You only need to use MD5 to encrypt the user's mailbox hash after merging into the above URL form. Of course, you also have the freedom to choose a custom image size. "D=MM" is the default avatar that the user displays without a Gravatar account. The "MM" option returns a gray picture of the silhouette of the person, called the "Enigma." and the "s=" option is used to set the pixel to return the size of the picture you given.

Of course Gravatar also have their own documents to describe the stitching technology URL!

Here userclass can return a picture of a user avatar, we need to integrate this into the User data layout (project directory/templates/user.html):

<!--extend Base layout-->
{% extends "base.html"%}
 
{% block content%}
<table>
  <tr Vali gn= "Top" >
    <td></td>
    <td> 
 

The bright spot in which we design userclass to return the user's avatar is that if one day we feel that the avatar on Gravatar's website is not the avatar we want, We only need to rewrite the Avatar processing function to return the address we want to (even if someone hotlinking point to our server, we can protect their own host), such a dozen need to modify so point, so the template is still automatic normal operation.

We have added the user Avatar section to the top of the user Details page, but at the bottom of the page we still have to show the article did not do, in front of the article we also need to show the user's head. Of course, the user Information page needs to be the same portrait of the article, but if the Avatar function to move to the homepage to give the article all show the author's head, that would be much better.

We only need to modify the template file slightly to achieve the article to display the corresponding author Avatar function (project directory/templates/user.html):

<!--extend Base layout-->
{% extends "base.html"%}
 
{% block content%}
<table>
  <tr Vali gn= "Top" >
    <td></td>
    <td> 
 

This is the end of our user profile page:

Micro Blog User Details page


Reusing child templates

User Information page shows the user's own article, but the homepage of the site needs to display different user articles at the moment. Here are two template files for displaying user stories. We can directly copy the processing of the code to display the article and then paste directly into the new template, in fact, that is not the ideal method, if one day we need to modify the display of the article, we need to update so those containing the article display code template files.


Instead, we will create a new template file to handle the function of the article display, and then include this file when you need to display the article.

Let's start by creating an empty template file, and then copy the code that shows the article in the User Profile page (project directory/templates/post.html):

<table>
  <tr valign= "Top" >
    <td></td> <td><i>{{post.author.nickname}}
  has released:</i><br>{{post.body}}</td>
  </tr >
</table>

Then we use JINJA2 's include function to call the template file (project directory/templates/user.html)

<!--extend Base layout-->
{% extends "base.html"%}
 
{% block content%}
<table>
  <tr VA lign= "Top" >
    <td></td>
    <td> 
 

Once we have the full page we can use the above method to invoke the template to display the article, but it is not urgent to say, in the later chapters of the tutorial.


more related personal information

Although the user Information page is more sophisticated, there is still a lot of information not displayed. Most users like to show themselves more information on the site, so we can let users fill out their own information displayed here. Of course, we can also record the user each time to visit the site, display to their own details page.


We need to update the database in order to display more and more information. Special need to add fields in UserClass (project directory/models.py):

 
Class User (db. Model):
  ID = db. Column (db. Integer, Primary_key = True)
  nickname = db. Column (db. String (+), unique = True)
  email = db. Column (db. String (in), index = true, unique = true) role
  = db. Column (db.  Smallinteger, default = Role_user)
  posts = db.relationship (' Post ', backref = ' author ', lazy = ' dynamic ')
  About_me = db. Column (db. String (140))
  Last_seen = db. Column (db. DateTime)

Each time we modify the database, we need to generate a new record (migration). Note that we remember to create a (migration) when processing data updates to the database, so let's look at the final results. We only need the following code to update the new two fields to the database:

./db_migrate.py

Of course the corresponding response script is

New migration saved as db_repository/versions/003_migration.py current
database Version:3

Now our new two fields are saved to the database. However, it is somewhat different to call this script under the window System.


If you do not support data migration, you will have to manually modify the database, otherwise you need to delete and then start again to create the data from scratch.

Next we need to modify the user Details page to display the field we just added (project directory/templates/user.html):


<!--extend Base layout-->
{% extends "base.html"%}
 
{% block content%}
<table>
  <tr Vali gn= "Top" >
    <td></td>
    <td>
       
 

Because we need to only when the user fills out these two fields, so we mainly use the JINJA2 to display these fields.

For this, for all users, both fields are empty and nothing is displayed.

The last field displayed (Last_seen) is especially good. It should be noted that we have set up the receive parameters (FLASK.G and Global, Asg.user) for registering user requests. That is, you need to log the user's login time in this best segment (project directory/views.py):

From datetime import datetime
#
... @app. Before_request
def before_request ():
  g.user = Current_User
  if g.user.is_authenticated ():
    G.user.last_seen = Datetime.utcnow ()
    db.session.add (g.user)
    db.session.commit ()

If you log in, you will be on the details page to display the final landing time, of course, if you refresh every time the page, the corresponding landing time will be automatically updated. This is because when the browser does not refresh once it will ask us to set the receive parameters above and update the database processing functions.


Here we record the standard UTC time zone. We also mentioned in the previous chapters how to store a timestamp for all time zones, this will have a negative error message because all the user's data pages show the UTC time zone, which I will explain in detail in the next section on the time and date.

To display more information about the user, we have to give them a link, the most suitable for the user information on the editing page.

Edit User Details

Create a User Profile Edit page that is so easy, we just need to create the following Web Form (project directory/forms.py):

From FLASK.EXT.WTF import Form, TextField, Booleanfield, Textareafield from
flask.ext.wtf import Required, Length
   class editform (Form):
  nickname = TextField (' nickname ', validators = [Required ()])
  About_me = Textareafield (' About_me ', validators = [Length (min = 0, max = 140)])

View template file (project directory/templates/edit.html):

<!--extend Base layout-->
{% extends "base.html"%}
 
{% block content%}
 
 

Finally, of course, the way to create a view (project directory/views.py):

From the forms import LoginForm, EditForm
 
@app. Route ('/edit ', methods = [' Get ', ' POST '])
@login_required
def Edit ():
  form = editform ()
  if Form.validate_on_submit ():
    g.user.nickname = Form.nickname.data
    G.user.about_me = Form.about_me.data
    db.session.add (g.user)
    db.session.commit ()
    Flash (' Your changes have been saved. ')
    Return Redirect (Url_for (' edit '))
  else:
    form.nickname.data = g.user.nickname
    form.about_me.data = G.user.about_me return
  render_template (' edit.html ',
    form = form)

To facilitate user editing, we need to add a link address to this page in the user's profile page (project directory/templates/user.html):

<!--extend Base layout-->
{% extends "base.html"%}
 
{% block content%}
<table>
  <tr Vali gn= "Top" >
    <td></td>
    <td>
       
 

But the only thing you need to decide is that the link is displayed only when the user browses to his or her profile page, rather than browsing through any of the profile pages.

The following is a screenshot of the latest profile page that contains our new addition so the fields also contain the words "About Me":


the last point is left to you to study.

Looks like through some of the above column making, personal information page feeling has been very perfect, right? Think carefully, yes, but we still have some bugs to fix.

I don't know if you found out.

Let me remind you, in the previous chapters, when we browsed the user login, I actually mentioned the bug. Now we've made the same mistake in the code piece above.

Think about it, and if you know what the problem is, you can say it in the comments below. I'll say the bug in detail in the next section and say how to fix it.


As before, I'll pack up the code I'm talking about today to download.

Download Address Microblog-0.6.zip.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.