Use flask to write a light blog (36)-use flask-restful to build RESTful API Five

Source: Internet
Author: User
Tags auth curl upgrades and downgrades

Blog Project Source: Https://github.com/JmilkFan/JmilkFan-s-Blog Directory

Table of Contents list put request delete request test Update operation on an existing posts record delete a record

List of the preceding text

Use flask to write a light blog (1)-Create a project
Use flask to write a light blog (2)-hello world.
Use flask to write a light blog (3)-(M) vc_ connect MySQL and SQLAlchemy
Use flask to write a light blog (4)-(M) VC_ create data models and tables
Use flask to write a light blog (5)-(M) Vc_sqlalchemy's CRUD detailed
Use flask to write a light blog (6)-(M) vc_models relationship (one to many)
Use flask to write a light blog (7)-(M) vc_models relationship (many to many)
Use flask to write a light blog (8)-(M) vc_alembic Manage database structure upgrades and downgrades
Use flask to write a light blog (9)-M (V) C_jinja Syntax Basics Quick overview
Write a light blog with flask. (a)-M (V) C_jinja common filters and flask special variables and methods
Use flask to write a light blog (one)-M (V) c_ CREATE VIEW function
Use flask to write a light blog (a)-M (V) C_ writes and inherits Jinja templates
Write a light blog with flask-m (V) c_wtforms service-side form test
Use flask to write a light blog (V)-M (v.) C_ Implementation Project Homepage Template
Write a light blog with flask-m (V) C_ Implementation Blog page comment form
Write a light blog with Flask-mv (C) _flask Blueprint Blueprint
Use flask to write a light blog (-MV) _ Apply blueprints to refactor projects
Use flask to write a light blog (18)-use Factory mode to generate application objects
Use flask to write a light blog (19)-to Bcrypt ciphertext store account information and implement user login form
Use flask to write a light blog (20)-Implement the authentication code by implementing the registration form and applying the reCAPTCHA
Use flask to write a light blog (21)-Combining reCAPTCHA authentication code to realize user registration and login
Use flask to write a light blog (22)-Implement the Add and edit pages of a blog post
Use flask to write a light blog (23)-Apply OAuth to implement Facebook third party login
Use flask to write a light blog (24)-use Flask-login to protect application security
Use flask to write a light blog (25)-use Flask-principal to implement role permissions
Use flask to write a light blog (26)-use Flask-celery-helper to implement asynchronous tasks
Use flask to write a light blog (27)-use Flask-cache to implement Web cache acceleration
Use flask to write a light blog (29)-use Flask-admin to implement background management SQLAlchemy
Use flask to write a light blog (30)-use Flask-admin to enhance the article management function
Use flask to write a light blog (31)-Implement filesystem management with Flask-admin
Use flask to write a light blog (32)-use flask-restful to build one of the RESTful APIs
Use flask to write a light blog (33)-use flask-restful to build the RESTful API II
Use flask to write a light blog (34)-use flask-restful to build the RESTful API three
Use flask to write a light blog (35)-use flask-restful to build the RESTful API fourPut request

Immediately following the first 4 articles, the implementation of the put and DELETE requests continues. The put request corresponds to the put () method of the resource class, which represents the update operation. So you still need to define the Post_put parser first.
Vim jmilkfansblog/controllers/flask_restful/parsers.py

Post_put_parser = Reqparse. Requestparser ()

post_put_parser.add_argument (
    ' title ',
    type=str)

post_put_parser.add_argument (
    ' text ',
    type=str)

post_put_parser.add_argument (
    ' tags ',
    type=str,
    action= ' append ')

post_put_parser.add_argument (
    ' token ',
    type=str,
    required=true,
    help= ' Auth token ') Required to update the posts. ')

Note: As you can see from the Post_put_parser parser, we allow only 4 parameters to be passed in, and there must be no shortage of token to ensure data security. Define the put () Update method for resource class Postapi
Vim jmilkfansblog/controllers/flask_restful/posts.py

... def put (self, post_id=none): "" "" "" would be execute to receive the HTTP Request methos ' put '. ""
            If not post_id:abort post = Post.query.filter_by (id=post_id). A () if not post: Abort (404) args = Parsers.post_put_parser.parse_args () user = User.verify_auth_token (args[' token '] If not User:abort (401) if user!= Post.user:abort (403) if args[' titl E ']: post.title = args[' title '] if args[' text ': Post.text = args[' text ' if args[
                ' Tags ']: For the item in args[' tags ']: Tag = Tag.query.filter_by (Name=item).
                   If Tag:post.tags.append (tag) Else:new_tag = Tag () New_tag.name = Item Post.tags.append (new_tag) Db.session.add (POST) db.session.co Mmit () return (pOst.id, 201) ... 

Note: The put () method is very similar to the post () method, so it is not here. DELETE Request

The implementation of the DELETE request is the simplest, and in general, you do not need to return any data, just return the correct HTTP status_int.
Vim jmilkfansblog/controllers/flask_restful/posts.py

    def delete (self, post_id=none): "" "" "" would be
        execute to receive the HTTP Request method ' delete '.

        "" If not post_id:
            abort

        post = Post.query.filter_by (id=post_id). (a)
        if not post:
            abort (404)

        args = Parsers.post_delete_parser.parse_args (strict=true)
        user = User.verify_auth_token (args[' token '])
        if user!= Post.user:
            Abort (403) # 'll be delete relationship the record with

        posts_tags too.
        # But you have to ensure the number of record equal with Len (post.tags)
        db.session.delete (POST)
        Db.session.commi T () return

        "", 204
Test update operations on an existing posts record
Mysql> SELECT * from posts where id= ' 1746b650-bcab-436b-82ab-7411e252b576 ';
+--------------------------------------+-----------+-------+--------------+------------------------------------ --+ |
ID |                                   title     | text  | publish_date | user_id                              |
+--------------------------------------+-----------+-------+--------------+------------------------------------ --+
| 1746b650-bcab-436b-82ab-7411e252b576 | Just Test | Hello | NULL         | 65cb9792-b876-49e7-b2c5-46468624199e |
+--------------------------------------+-----------+-------+--------------+------------------------------------ --+
1 row in Set (0.00 sec)
Get Token
jmilkfan@jmilkfan-devstack:/opt/jmilkfan-s-blog$ curl-d "username=<username>"-D "password=<password>" Http://localhost:8089/api/auth
{
    "token": " eyjhbgcioijiuzi1niisimv4cci6mtq4mzm2mjexnywiawf0ijoxndgzmzyxnte3fq.eyjpzci6ijy1y2i5nzkylwi4nzytndllny1immm1ltq2ndy4nji0mt K5zsj9.2r7f-szjs2u8zafqyl7ouypffgildjemvwimpuihxd0 "
}
Put request
jmilkfan@jmilkfan-devstack:/opt/jmilkfan-s-blog$ curl-x put-d "Title=just Test put"-D "Text=hello Guys"-D "Tags=Python "-D" Tags=flask "D" token= eyjhbgcioijiuzi1niisimv4cci6mtq4mzm2mjexnywiawf0ijoxndgzmzyxnte3fq.eyjpzci6ijy1y2i5nzkylwi4nzytndllny1immm1ltq2ndy4nji0mt K5zsj9.2r7f-szjs2u8zafqyl7ouypffgildjemvwimpuihxd0 "http://localhost:8089/api/posts/ 1746b650-bcab-436b-82ab-7411e252b576
"1746b650-bcab-436b-82ab-7411e252b576"
Results
Mysql> SELECT * from posts where id= ' 1746b650-bcab-436b-82ab-7411e252b576 ';
+--------------------------------------+---------------+------------+--------------+--------------------------- -----------+
| ID                                   | title |         Text       | publish_date | user_id
| +--------------------------------------+---------------+------------+--------------+--------------------------- -----------+
| 1746b650-bcab-436b-82ab-7411e252b576 | Just Test Put | Hello Guys | NULL         | 65cb9792-b876-49e7-b2c5-46468624199e |
+--------------------------------------+---------------+------------+--------------+--------------------------- -----------+
1 row in Set (0.00 sec)
Delete a record
jmilkfan@jmilkfan-devstack:/opt/jmilkfan-s-blog$ curl-x delete-d "token= eyjhbgcioijiuzi1niisimv4cci6mtq4mzm2mjkzmywiawf0ijoxndgzmzyymzmzfq.eyjpzci6ijy1y2i5nzkylwi4nzytndllny1immm1ltq2ndy4nji0mt K5zsj9.b8isy5fb6ad_pyrjxnvqnyuxxumreiob-rlhtyvycxu "http://localhost:8089/api/posts/1746b650-bcab-436b-82ab-7411e252b576
Results
Mysql> SELECT * from posts where id= ' 1746b650-bcab-436b-82ab-7411e252b576 ';
Empty Set (0.00 sec)

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.