通过命令行发布Python数据

时间:2018-07-06 08:16:58

标签: python rest python-requests

我为此很努力。已经阅读了requests API文档,但无法完美执行。

我已经编写了一个python脚本,该脚本旨在获取GETPOST',and the remaining REST operations through a command line. GET works fine, and any request from the localhost`网址。

但是,我无法POST使用新数据。例如,GET方法是这样发出的:

request.py -r get -f 1 -u http://127.0.0.1:5002/user 

和userID 1的数据以JSON格式显示。 user是数据库的名称,其中包含这些操作。

类似地,我想以post格式JSON新数据

我尝试了此命令,但收到错误

request.py -r get -f 7 -u http://127.0.0.1:5002/user {'user':'abc','email':xyz@abc.com} 

getAddrInfoFailed

enter image description here

以下是用于创建数据库以及请求的代码

from flask import Flask, request
from flask_restful import Resource, Api
import sqlite3
import re

app = Flask(__name__)
api = Api(app)


def validate_email(email):
    match = re.search('^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,4})$', email)
    if match:
        return True
    else:
        return False


def validate_username(username):
    match = re.search('^[A-Za-z0-9_-]{3,20}$', username)
    if match:
        return True
    else:
        return False


def validate_id(id):
    if id.isdigit():
        return True
    else:
        return False


class Users(Resource):
    def get(self, id):
        try:
            conn = sqlite3.connect('curd.db')
            cursor = conn.cursor()
            if validate_id(id):
                query = cursor.execute("SELECT * FROM user WHERE id=?", [int(id), ])
                row = query.fetchone()
                if row:
                    return {'item': {'id': row[0], 'username': row[1], 'email': row[2]}},200
                else:
                    return {'MESSAGE': 'USER NOT FOUND'}, 404
            else:
                return {'MESSAGE': 'INVALID INPUT'}, 400
        except:
            conn.rollback()
        finally:
            conn.commit()
            conn.close()

    def post(self, id):
        try:
            conn = sqlite3.connect('curd.db')
            cursor = conn.cursor()
            usr = request.get_json()
            username = usr['username']
            email = usr['email']
            if validate_id(id) is True and validate_username(username)is True and validate_email(email) is True:
                query = cursor.execute("SELECT * FROM user WHERE id=?", [int(id), ])
                row = query.fetchone()
                if row:
                    return {'MESSAGE': 'USER ID ALREADY EXISTS'}, 400

                else:
                    cursor.execute("INSERT INTO user(id, username, email) VALUES(?,?,?)", [id, username, email])
                    return {'response': 'Success'},201
            else:
                 return {'MESSAGE': 'INVALID INPUT'}, 400
        except:
            conn.rollback()
        finally:
            conn.commit()
            conn.close()

    def put(self, id):
        try:
            conn = sqlite3.connect('curd.db')
            cursor = conn.cursor()
            usr = request.get_json()
            updated_name = usr['username']
            updated_email = usr['email']
            if validate_id(id) and validate_username(updated_name) and validate_email(updated_email):
                query = cursor.execute("SELECT * FROM user WHERE id=?", [int(id), ])
                row = query.fetchone()
                if row:
                    cursor.execute("UPDATE user SET username = '" + str(updated_name) + "',email = '" + str(updated_email) + "' WHERE id = %d" % int(id))
                    return {'response': 'Success'},200
                else:
                    return {'MESSAGE': 'USER NOT FOUND'}, 404
            else:
                 return {'MESSAGE': 'INVALID INPUT'}, 400
        except:
            conn.rollback()
        finally:
            conn.commit()
            conn.close()

    def delete(self, id):
        try:
            conn = sqlite3.connect('curd.db')
            cursor = conn.cursor()
            if validate_id(id):
                query = cursor.execute("SELECT * FROM user WHERE id=?", [id, ])
                row = query.fetchone()
                if row:
                    conn.execute("DELETE FROM user WHERE id = %d" % int(id))
                    return {'response': 'Success'},200
                else:
                    return {'MESSAGE': 'USER NOT FOUND'}, 404
            else:
                 return {'MESSAGE': 'INVALID INPUT'}, 400
        except:
            conn.rollback()
        finally:
            conn.commit()
            conn.close()


api.add_resource(Users,'/user/<string:id>',methods=['GET','POST','PUT','DELETE'])
if __name__ == '__main__':
    app.run(port=5002, debug=True)

requests.py

import requests
import json
import sys
from optparse import OptionParser, make_option

if len(sys.argv) <= 1:
    print('Need at least 1 argument.')
    print("Add -h for Help")
    sys.exit(1)

parser = OptionParser()
parser.add_option('-r', '--request', help="Request Type['GET','POST','PUT','DELETE']",default="")
parser.add_option('-f', '--id', help='id')
parser.add_option('-u', '--url', help="URL String",default="")
(options, args) = parser.parse_args()

print("ID = "+options.id)
print("Request Type = "+options.request)
print("Request URL = "+options.url)

url = options.url+"/"+options.id
data = ''
payload= {'key1':'value1','key2':'value2'}
if options.request == "get":
    response = requests.get(url, data=data)
elif options.request=="post":
    response = requests.post(url, params=payload)
else:
    print("Invalid Request..!!")
print(response.text)

0 个答案:

没有答案