Flask Developing RESTful API series (3)

Source: Internet
Author: User

The above two chapters, mainly about the basic configuration, today we do a more interesting thing, for each customer plus an avatar picture. If we save the picture in their own server, for the server is a bit high, each time the download, will block the network interface, if 1000 people at the same time access to this picture, will completely scrap the entire network. If you are like me, in a small company, do not have their own professional picture server, and want to use pictures, it is like me, try to use seven bull bar. This is really a very good cloud product.

First, add a field to the model,

1 #Coding:utf-82  fromSQLAlchemyImportCreate_engine, ForeignKey, Column, Integer, String, Text, DateTime,3 And_, Or_, Smallinteger, Float, DECIMAL, DESC, ASC, Table, join, event4  fromSqlalchemy.ormImportrelationship, Backref, Sessionmaker, Scoped_session, aliased, mapper5  fromSqlalchemy.ext.declarativeImportDeclarative_base6  fromSqlalchemy.ext.hybridImportHybrid_property, Hybrid_method7  fromSqlalchemy.orm.collectionsImportattribute_mapped_collection8 Importdatetime9 TenEngine = Create_engine ("Mysql://root:[email Protected]:3306/blog01?charset=utf8", pool_recycle=7200) One  ABase =declarative_base () -  -Db_session = Scoped_session (Sessionmaker (autocommit=False, theAutoflush=False, -Bind=engine)) -  -Base.query =Db_session.query_property () +  -  + classUser (Base): A     __tablename__='User' at  -id = Column ('ID', Integer, primary_key=True) -Phone_number = Column ('Phone_number', String (one), index=True) -Password = Column ('Password', String (30)) -Nickname = Column ('Nickname', String (+), Index=true, nullable=True) -Head_picture = Column ('head_picture', String (default=),"') inRegister_time = Column ('Register_time', DateTime, Index=true, default=Datetime.datetime.now) -  to  + if __name__=='__main__': -Base.metadata.create_all (Engine)

After the increase, start consolidating the database. How do we do that? Flask suggest that we can use a third-party plug-in, Flask-migrate, other its bottom is the use of alembic, since we know, you can directly use Alembic. Why use Alembic directly? I believe everyone also see, I this code and other flask with SQLAlchemy not the same, many people are directly using Flask-sqlalchemy plug-in, but I do not like. Because this will bind me, why use flask, is because it is free, how to change how to change, if in this directory, write a script, direct reference can, there is no need to be in the CURRENT_APP environment. This is just a person's preference, like with Flask-sqlalchemy can continue to use.

First install Alembic, because previously installed flask-migrate, so the direct use of Apt-get install Alembic can be.

First, under the BLOG01 directory,

Alembic Init my_migration

At this point, the My_migration directory is generated and the directory is as follows:

At this time to edit the Alembic.ini, this is the Alembic configuration file, basically as long as you modify a place.

Sqlalchemy.url = MySQL://root:[email Protected]:3306/blog01?charset=utf8

Actually is to tell Alembic, every time I revise, you move which database

Next is the program, Alembic script is placed in the env.py inside, in fact, just want to modify a place, is to tell Alembic, I corresponding ORM with which engine.

Under normal circumstances, we just need to add two lines of code enough, as the ideal situation should be

 from Import  = Base.metadata

If we're just doing this, we'll get an import error, we can't find the package, it doesn't know how you're going to reference the package, so we're going to add the current directory to the environment variable and make it available globally.

However, the import package error, be sure to put the top of the BLOG01 also in the package, the price is too big, as standard way, put all the files in the app.

Import OS Import  = os.path.dirname (__file__'/... ' sys.path.append (Root)  from Import  = Base.metadata

Then the structure becomes this way.


Run the terminal, navigate to the BLOG01 directory,

' Add column Head_picture ' INFO  [Alembic.runtime.migration] Context impl mysqlimpl.info  [alembic.runtime.migration] would assume non-  Transactional ddl.info  'user.head_picture'  done 

Generate an edit script,

Run again

Head

You can, go to the database to see it, has been more than an avatar column.

This way to say more, alembic can add, delete columns, but to change the column some do not automatically support, you need to modify a little bit. Next I do an experiment, head_picture from string (100) to String (120), first we check the database actual situation.

Mysql>Show create table user;+-------+------------------------------------------------------------------------------------------------------ --------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- -------------------------------------------+| Table |                                                                                                                                                                                                                                        Create Table |+-------+- ----------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- -------------------+| user |CREATE TABLE ' user ' ('ID`int( One) not NULL auto_increment, ' phone_number ' varchar ( One) DEFAULT NULL, ' password ' varchar ( -) DEFAULT NULL, ' nickname ' varchar ( -default NULL, ' Register_time ' datetime DEFAULT null, ' head_picture ' varchar ( -) DEFAULT NULL, PRIMARY KEY ('ID'), key ' Ix_user_nickname ' (' nickname '), Key ' Ix_user_phone_number ' (' Phone_number '), key ' Ix_user_register_time ' ( ' Register_time ') ENGINE=innodb auto_increment=2DEFAULT Charset=utf8 |+-------+--------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------+1RowinchSet (0.00sec) MySQL>

Look at the code above, Head_picture is a string (100), if we follow the traditional approach, Alembic is unable to modify the field, the official document also introduced, the Interception of field types and modify the field name, the need to own handwriting script. Don't worry, it's really very, very simple.

First, change the head_picture inside the model.py to 120.

    Head_picture = Column ('head_picture', String (+), default=')

Then generate the script

' alter column Head_picture string120 '

Will generate this script file, open it, see the code

def upgrade ():     # # # Commands auto generated by Alembic-please adjust! # # #    Pass    # # # End Alembic Commands # # # def downgrade ():     # # # Commands auto generated by Alembic-please adjust! # # #    Pass    # # # End Alembic Commands # # #

It didn't write anything, it was written by ourselves, and it was very, very easy. The code is as follows.

 fromSqlalchemy.dialectsImportMySQLdefupgrade ():## # Commands auto generated by Alembic-please adjust! # # #Op.alter_column ('User','head_picture'Sa. String (length=120), Existing_type=mysql. VARCHAR (120))    ## # End Alembic Commands # # #defdowngrade ():## # Commands auto generated by Alembic-please adjust! # # #Op.alter_column ('User','head_picture'Sa. String (length=100), Existing_type=mysql. VARCHAR (100))    ## # End Alembic Commands # # #

See no, if a little familiar with MySQL, know what meaning, is directly to the varchar (100) to varchar (120), if later degraded, and then replaced by varchar (100). is not very simple, OK, execute this script.

$ alembic Upgrade Head

Check the effect.

Mysql>Show create table user;+-------+------------------------------------------------------------------------------------------------------ --------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- --------------------------------------------+| Table |                                                                                                                                                                                                                                        Create Table |+-------+ ---------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- ----------------------+| user |CREATE TABLE ' user ' ('ID`int( One) not NULL auto_increment, ' phone_number ' varchar ( One) DEFAULT NULL, ' password ' varchar ( -) DEFAULT NULL, ' nickname ' varchar ( -default NULL, ' Register_time ' datetime DEFAULT null, ' head_picture ' varchar ( -) DEFAULT NULL, PRIMARY KEY ('ID'), key ' Ix_user_nickname ' (' nickname '), Key ' Ix_user_phone_number ' (' Phone_number '), key ' Ix_user_register_time ' ( ' Register_time ') ENGINE=innodb auto_increment=2DEFAULT Charset=utf8 |+-------+--------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- -----------------------------------------------------------------+1RowinchSet (0.00Sec

See if Head_picture is becoming 120, is it very simple? Well, this chapter is about this, and in the next chapter, we'll show you how to upload images by seven cows.

Flask Developing RESTful API series (3)

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.