Tornado 08 Database-orm-sqlalchemy-table relationships and simple login registration

Source: Internet
Author: User

Tornado 08 Database-orm-sqlalchemy-table relationships and simple login registration

Introduction

#在数据库, The so-called table relationship, is only the human thought of the added table and the relationship between the table, just logically think of the relationship, in fact, the table in the database is not so-called table relationship

One or one to a table relationship

Module

#the corresponding module needs to be created first, using the previously established user and UserdetailsRelationship fromSqlalchemyormImportRelationship#Add the following code to the Userdatails:Userdetail = Relationship ('User', backref='Details', uselist=false,cascade=' All')#Userow = Session.query (User). Get (1) Rows.details

Relationship

Userdetail = Relationship ('User', Backref ='Details', uselist=false,cascade=' All')#there must be foreignkey when using relationship.#class name User, which represents the associated module#in the subclass, add details to the parent class user via the relationship inside the Backref property#Uselist=false represents relationship no longer represents a one-to-many relationship, indicating a one-to-one relationship.#cascade means automatic relationship processing, similar to the on DELETE in MySQL#Cascade all of the optional string entries: 1, all, the operation is automatically processed to the associated object, 2, Save_update, the associated object is automatically added to the session, 3, delete, the associated object is automatically removed from the conversation; 4, Delete-orphan, attribute, the associated object is deleted automatically in the session, 5, Merge,session.merge () is the associated object, 6, Refresh-expire,session.expire () will handle the associated object, 7, expunge, Session.expunge () processes the associated object#automatically add properties#in this case, the user does not have the details of this property, but after adding relationship inside the userdetails, the user instance will automatically add the Details property#Relationship#A table relationship is a logical relationship, but there is nothing in MySQL that directly describes a table relationship, a foreign key constraint is a representation, and a foreign key is a constraint between tables that can be used to represent this relationship#in SQLAlchemy, this relationship represents a one-to-many relationship, of course, we can change the relationship by the parameters, it is the default is a one-to-many relationship, and this relationship is sqlalchemy inside, and the database does not have any relationship, But relationship is used with foreign keys.

#Enter the code in the relationship.py fromConnectImportSession fromUser_modulesImportuser,userdetailsrows= Session.query (User). Get (2)#get data information with ID 2Print(rows)Print(Rows.username)Print(rows.details) rows= Session.query (userdetails). Get (1)Print(rows)Print(Rows.userdetail)#as long as a one-to-one relationship is determined, the sub-class Userdetail and the details property of the parent class can get the corresponding data

Two, many-to-many relations

# The relationship between the user and the server can be regarded as a one-to-many relationship, but the user-reproduced relationship can be regarded as a many-to-many relationship, how to express many-to-many relationships in SQLAlchemy
#Add in user_modules.py, remember to import the table module fromSQLAlchemyImporttableuser_article= Table ('user_article', Base.metadata, Column ('user_id', Integer,foreignkey ('user.id'), primary_key=True), Column ('article_id', Integer,foreignkey ('article.id'), primary_key=True)) #Middle Table notationclassArticle (Base):#Article Module    __tablename__='article'ID= Column (integer,primary_key=true,autoincrement=True) Content= Column (String), nullable=True) Create_time= Column (datetime,default=DateTime.Now) Article_user= Relationship ('User', backref='article', secondary=user_article)#the difference with the above is that there is no uselist,secondary parameter passed into the intermediate table    def __repr__(self):return 'article (id=%s,content=%s,create_time=%s)'%(Self.id, Self.content, Self.create_time)

Three, package management

# How do I import the module after it is written?
# import directly into the module:  from Import # import user from the user_modules.py under the data package
 #   This involves package management   #   package concept  #   Put a lot of modules into a folder, you can form a package  #   package management  Span style= "COLOR: #008000" >#   When placing many modules in a folder, to facilitate the referencing of modules in the package, introduce package management  __init__  .py  #   in package management, add this module, the package name can be accessed directly through the property access to the object in this module, the module does not add may not error, but the specification is to add, the file content can be empty  #   relative path import   #   
# Relative path Import # Introduction Effect # In a package, if the module in the package is to be imported into another module in the same package, you must use this method to import # How to use  from Import obj (as new_name) # introduction of future effects # When this import occurs in a module, the module cannot be run directly and is imported directly

Four, simple login

ImportTornado.httpserverImportTornado.ioloopImporttornado.optionsImportTornado.web fromTornado.optionsImportdefine,optionsImport TimeImportUtil.ui_methodsImportUtil.ui_modules fromData.user_modulesImportUser#Import a module packageDefine ('Port', Default=8080,help ='Run Port', type=int)defhaha ():return 'This is Hahahaah'classLoginhandler (tornado.web.RequestHandler):defGet (self, *args, * *Kwargs): Self.render ('lesson2.html')    defPost (self, *args, * *Kwargs): User= Self.get_arguments ('name') Password= Self.get_argument ('Password',"') Username=user.by_name (User)ifUsername andPassword = =Username[0].password:self.render ('login_07.html', username=username)Else: Self.write ('incorrect user name or password') Application=tornado.web.Application (Handlers=[(R'/login', Loginhandler),], Template_path='Templates', Static_path='Static', Autoescape=None, Ui_methods=Util.ui_methods, Ui_modules=util.ui_modules, Debug=True)if __name__=='__main__': Tornado.options.parse_command_line () Http_server=tornado.httpserver.HTTPServer (application) Http_server.listen (Options.port) tornado.ioloop.IOLoop.instance () . Start ()
<! DOCTYPE html>"en">"UTF-8"> <title>Title</title> <link rel="stylesheet"href="Css/bootstrap.css"> <style> *{margin:0;        padding:0; }    </style>    {%ifUsername%Welcome user {{Username}} login<br> "{{Static_url (' images/1.jpg ')}}"Width=" -"height=" -"> <br>    {%Else%} You are not signed in {% END%}</body>
# import inside the user_module.py  from Import base,session # write inside the user class     @classmethod    def  By_name (cls,name):        return  #  to get the class name through the adorner

Tornado 08 Database-orm-sqlalchemy-table relationships and simple login registration

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.