Flask developed restful api series (3) and flaskrestful

Source: Internet
Author: User

Flask developed restful api series (3) and flaskrestful

The above two chapters mainly focus on basic configurations. Today we are doing something interesting and adding an avatar image to each customer. If we store images on our own servers, we have high requirements for servers. Every time we download images, we will block Network Interfaces. IF 1000 people access this image at the same time, the entire network will be completely decommissioned. If you don't have your own professional image server in a small company like me and want to use images, try qiniu like me. This is really a good cloud product.

First, add a field to the model,

 1 # coding:utf-8 2 from sqlalchemy import create_engine, ForeignKey, Column, Integer, String, Text, DateTime,\ 3     and_, or_, SmallInteger, Float, DECIMAL, desc, asc, Table, join, event 4 from sqlalchemy.orm import relationship, backref, sessionmaker, scoped_session, aliased, mapper 5 from sqlalchemy.ext.declarative import declarative_base 6 from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method 7 from sqlalchemy.orm.collections import attribute_mapped_collection 8 import datetime 9 10 engine = create_engine("mysql://root:a12345678@127.0.0.1:3306/blog01?charset=utf8", pool_recycle=7200)11 12 Base = declarative_base()13 14 db_session = scoped_session(sessionmaker(autocommit=False,15                                          autoflush=False,16                                          bind=engine))17 18 Base.query = db_session.query_property()19 20 21 class User(Base):22     __tablename__ = 'user'23 24     id = Column('id', Integer, primary_key=True)25     phone_number = Column('phone_number', String(11), index=True)26     password = Column('password', String(30))27     nickname = Column('nickname', String(30), index=True, nullable=True)28     head_picture = Column('head_picture', String(100), default='')29     register_time = Column('register_time', DateTime, index=True, default=datetime.datetime.now)30 31 32 if __name__ == '__main__':33     Base.metadata.create_all(engine)

After the addition, start to integrate the database. How can this problem be solved? We recommend that you use a third-party plug-in, flask-migrate. The underlying layer of flask is alembic. As we know, You can directly use alembic. Why directly use alembic? As you can see, my code is different from other flask uses sqlalchemy. Many people directly use the flask-sqlalchemy plug-in, but I don't like it very much. This is because it binds me. Why should we use flask? It is because it is free and can be changed if we want to change it. In the future, if we write a script in this directory, we can directly reference it, there is no need to be in the current_app environment. This is just my preference. If you prefer flask-sqlalchemy, you can continue to use it.

 

First install alembic. Because flask-migrate has been installed before, you can directly use apt-get install alembic.

First in the blog01 directory,

alembic init my_migration

At this time, the my_migration directory will be generated, and the directory is as follows:

In this case, edit alembic. ini, which is the configuration file of alembic. You only need to modify it.

sqlalchemy.url = mysql://root:a12345678@127.0.0.1:3306/blog01?charset=utf8

It is actually telling alembic which database do you need to change every time I modify it

The next step is the program. The alembic script is placed in env. py. In fact, it only needs to be modified to tell alembic which engine is used for the corresponding orm.

Under normal circumstances, we only need to add two lines of code. It should be as expected.

from model import Basetarget_metadata = Base.metadata

If this is the case, an import error will occur and the package cannot be found. It does not know how to reference the package. Therefore, we need to add the current directory to the environment variable to make it globally available.

But it is still a package import error. You must put blog01 at the top of the package in the package, which is too costly. It is better to put all the files in the app according to the standard method.

import osimport sysroot = os.path.dirname(__file__) + '/..'sys.path.append(root)from model import Basetarget_metadata = Base.metadata

Then the structure becomes like this.


Run the terminal and go to the blog01 directory,

>>alembic revision --autogenerate -m 'add column head_picture'INFO  [alembic.runtime.migration] Context impl MySQLImpl.INFO  [alembic.runtime.migration] Will assume non-transactional DDL.INFO  [alembic.autogenerate.compare] Detected added column 'user.head_picture'  Generating /home/yudahai/PycharmProjects/blog01/my_migration/versions/9a12387b186_add_column_head_picture.py ... done

Generate the editing script,

Run again

>>alembic upgrade head

Now you can go to the database and check it out. There is an additional profile picture column.

You can add or delete columns for alembic, but it is not automatically supported for changing columns. You need to modify the columns by yourself. Next I will conduct an experiment to change head_picture from String (100) to String (120). First, let's check the actual situation of the database.

mysql> show create table user;+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+| Table | Create Table                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+| user  | CREATE TABLE `user` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `phone_number` varchar(11) DEFAULT NULL,  `password` varchar(30) DEFAULT NULL,  `nickname` varchar(30) DEFAULT NULL,  `register_time` datetime DEFAULT NULL,  `head_picture` varchar(100) 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=2 DEFAULT CHARSET=utf8 |+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+1 row in set (0.00 sec)mysql> 

According to the code above, head_picture is String (100). If we follow the traditional method, alembic cannot modify the field. The official document also introduces how to intercept the field type and modify the field name, you need to manually write the script. Don't worry, it's actually very simple.

First, modify head_picture in model. py to 120.

    head_picture = Column('head_picture', String(120), default='')

Then generate the script

$ alembic revision --autogenerate -m 'alter column head_picture string120'

This script file is generated, opened, and read 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 does not write anything. It is very easy for us to write it by ourselves. The Code is as follows.

from sqlalchemy.dialects import mysqldef upgrade():    ### 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 ###def downgrade():    ### 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 ###

If you are a little familiar with mysql, what does it mean? Change varchar (100) to varchar (120) directly. If you downgrade it later, change it to varchar (100 ). Is it very simple? Well, execute this script.

$ alembic upgrade head

Check the effect

mysql> show create table user;+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+| Table | Create Table                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+| user  | CREATE TABLE `user` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `phone_number` varchar(11) DEFAULT NULL,  `password` varchar(30) DEFAULT NULL,  `nickname` varchar(30) DEFAULT NULL,  `register_time` datetime DEFAULT NULL,  `head_picture` varchar(120) 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=2 DEFAULT CHARSET=utf8 |+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+1 row in set (0.00 sec)

Check if head_picture is changed to 120. Is it easy? Now, this chapter introduces how to upload images through qiniu.

 

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.