python做http請求

rodertW發表於2019-02-14

基於flask,封裝http服務

 

#客戶端
import requests


url = 'http://127.0.0.1:16701/mail/sendmail'
response = requests.post(url,data={"subject":"subject","body":"Test","to":["test@163.com","wej@qq.com"]})
print(response)
print(response.text)
#伺服器端

# coding: utf-8
#encoding: utf-8
 
import json
import requests
from flask import Flask
from flask_restful import Api
from flask_restful import Resource
from flask_restful .reqparse import RequestParser
import datetime

app = Flask(__name__)
api = Api(app)
class sends:

class QueryApi(Resource):
    def __init__(self):
        # 使用者請求引數校驗
        self.reqparse = RequestParser()
        self.reqparse.add_argument('subject', required=False, type=str,default='error')
        self.reqparse.add_argument('body', required=True, type=str)
        self.reqparse.add_argument('format', required=False, type=str,default='plain')
        self.reqparse.add_argument('from', required=False, type=str,default='youxiang@qq.com')
        self.reqparse.add_argument('to', required=True, type=str,action='append')

        super(QueryApi, self).__init__()

        
    def post(self):
        # print('here')
        params = self.reqparse.parse_args()
        nowtime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')#現在時間
        print(nowtime)
        print(params)

        print(params)
        # print(q2)
        return {'result':params}

BASE_URL = '/mail'
api.add_resource(QueryApi, '%s/sendmail' % BASE_URL, endpoint='sendmail')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=16701)

 

相關文章