zoukankan      html  css  js  c++  java
  • python http server handle json

    用Python实现一个http server

    # python2
    # coding = utf-8
    
    from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
    import json
    
    class RequestHandler(BaseHTTPRequestHandler):
        def _set_headers(self):
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
    
        def do_GET(self):
            response = {
                'status':'SUCCESS',
                'data':'hello from server'
            }
    
            self._set_headers()
            self.wfile.write(json.dumps(response))
    
        def do_POST(self):
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            print 'post data from client:'
            print post_data
    
            response = {
                'status':'SUCCESS',
                'data':'server got your post data'
            }
            self._set_headers()
            self.wfile.write(json.dumps(response))
    
    def run():
        port = 80
        print('Listening on localhost:%s' % port)
        server = HTTPServer(('', port), RequestHandler)
        server.serve_forever()
    
    run()

    python post json的两种方法:

    # python2
    # coding = utf-8
    
    import json
    import urllib2
    
    data = {
        'key1':'value1',
        'key2':'value2'
    }
    
    req = urllib2.Request('http://server_ip:server_port')
    req.add_header('Content-Type', 'application/json')
    
    response = urllib2.urlopen(req, json.dumps(data))
    
    print(response.read())
    # python3
    # coding = utf-8
    
    import requests
    
    mydict = {
        'key1': 'value1',
        'key2': 'value2'
    }
    
    r = requests.post("host:port/post", json=mydict)
    print(r.status_code)
    print(r.json())
  • 相关阅读:
    HDUoj(1002)A + B Problem II
    HIT Summer 20180731
    Windows10下python3.5对维基百科语料用word2vec进行训练寻找同义词相似度
    关键词抽取
    win10+python遇到:Using TensorFlow backend.错误
    Windows下Python3.5+numpy+keras+tesorflow的环境配置
    常用的一些序列号
    Umbraco扩展开发
    Umbraco Content属性
    Windows查看端口占用
  • 原文地址:https://www.cnblogs.com/gattaca/p/7301282.html
Copyright © 2011-2022 走看看