Getting Started with Python web py (10)-Implementing forum Registration

Source: Internet
Author: User
Tags md5 set cookie setcookie
When a user wants to publish an article in a forum, it is necessary to register an account before they can log in and publish articles. So let's move on to the previous example to implement the registration function.
Above the underlying code in the previous example, the code example is attached below:
http://blog.csdn.net/caimouse/article/details/79343362

First to add a URL to the main program entry file forum.py the registered page, as follows:

URLs = (
'/', ' Index ',
'/register ', ' register ',
)

The addition of '/register ', ' register ', in this line, is to implement the Association of the Registration class, and then to create the Register class register:

Class Register:
    def get (self): return
        titled_render (' register '). Register ()

    def POST (self):
        try:
            i = Web.input ()
            user_id = model. User (). New (I.email, I.username, I.password)
        except Exception as E:
            print (e) return
            Titled_render (). Failed (' mailbox or account number already exists, please <a href= '/register ' > Registration </a> ')
        else:
            if user_id:
                # Set Cookies
                Web.setcookie (' user_id ', str (user_id), settings. Cookie_expires)
                raise Web.seeother ('/user/%d '% user_id)
In the registration class implementation of two methods, the first is a get method, mainly display a page, let the user input data, I do not know whether you remember the previous example, is it "the introduction of Python Web py (5)-to write the data of the Web page to the database", the realization is the same. The second method is post, which is to write the data submitted by the page to the database.
This line of code titled_render (' register '). Register () is to call the template register.html to render the display, let the user enter data, display the results as follows:


When the user presses the Submit registration button, the Post method will submit data to the server, you can use Web.input () to obtain the appropriate data, where to obtain the email address, user name and password, and finally through the model in class user to add to the database to save.

Call the new function as follows:

def new (self, email, username, password):
        Pwdhash = hashlib.md5 (Password.encode (' Utf-8 ')). Hexdigest ()
        return Db.insert (' Users ', Email=email, Name=username, Password=pwdhash,
                         picture= '/static/img/user_normal.jpg ', Description= "")
In this function, first call the Hashlib Library's MD5 algorithm to sign the password, so that the original password can not be seen from the database, followed by the call to the Db.insert to perform the database operation, the registration data into the database table, so that the entire registration process completed. If you successfully register, you open the Personal information page. Otherwise, you will be prompted with an unexpected error (Titled_render (). Failed), such as duplicate registration, and so on.

register.html Template:

$def with () <form id= "register" action= "" method= "POST" > <table> <tbody> <tr> <td& Gt;<label for= "Email" > Email </label></td> <td><input type= "text" id= "email" name= "email"/& Gt;<span class= "Validate_tip" ></span></td> </tr> <tr> <td><label fo R= "username" > account </label></td> <td><input type= "text" id= "username" name= "username"/>&lt ; span class= "Validate_tip" ></span></td> </tr> <tr> <td><label for= "pas Sword "> Password </label></td> <td><input type=" password "id=" password "name=" password "/><s" Pan class= "Validate_tip" ></span></td> </tr> <tr> <td><label for= "PASSW Ord_again "> Password confirmation </label></td> <td><input type=" password "id=" password_again "name=" password _again "/><span class= "Validate_tip" ></span></td> </tr> <tr><td><input type= "Submit" id= "Registe" R_btn "value="/></td></tr> </tbody> </table> </form>

The failed.html template file is as follows:

$def with (error)

<p>$:error</p>

forum.py file:

#python 3.6 #蔡军生 #http://blog.csdn.net/caimouse/article/details/51749579 # Import Web import settings I 
Mport Model Import Util import OS import JSON import hashlib urls = ('/', ' Index ', '/register ', ' Register ',) # App = Web.application (URLs, Globals (), autoreload = True) ##### BEG: template rendering ##### CurDir = Os.path.abspath (Os.path.dirnam E (__file__)) templates = CurDir + '/templates/' Def render (params={}, Partial=false): Global_vars = {**settings. 
        Global_params, **params} if Partial:return web.template.render (templates, globals=global_vars) Else: Return Web.template.render (templates, base= ' layout ', Globals=global_vars) def titled_render (subtitle= '): su Btitle = subtitle + '-' if subtitle Else ' return render ({' title ': Subtitle + settings.) Site_Name, ' make_html ': util.make_html, ' Trim_utf8 ': Util.trim_utf8, ' menu ': Util.menu (model.
 User ())}) ##### end: Template Rendering ##### class Index:def get (self):       i = web.input (page= ' 1 ') page = Int (i.page) page_posts, Page_count = model.
        Post (). List (page) return Titled_render (). List (page_posts, Page_count, page) class Register:def get (self): Return Titled_render (' register '). Register () def POST (self): try:i = Web.input () user_ id = model. User (). New (I.email, I.username, I.password) except Exception as E:print (e) return titled_
                Render (). Failed (' mailbox or account number already exists, please <a href= '/register ' > Registration </a> ') else:if user_id: # Set Cookie Web.setcookie (' user_id ', str (user_id), settings. Cookie_expires) Raise Web.seeother ('/user/%d '% user_id) # exported Wsgi function application = App.wsgifunc () # #
 ### Debug ##### If __name__ = = "__main__": App.run ()
Version management and combat in SVN under Windows
http://edu.csdn.net/course/detail/2579
Visual Studio 2015 Basic use of developing C + + programs
http://edu.csdn.net/course/detail/2570
Using the PROTOBUF protocol in VC2015.
http://edu.csdn.net/course/detail/2582
Learn to use MySQL database in VC2015
http://edu.csdn.net/course/detail/2672


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.