python搭建web服务

import json
from urlparse import parse_qs
from wsgiref.simple_server import make_server
import os
import re
from django.http import HttpResponse
from django.conf import settings
settings.configure()

# 定义函数,参数是函数的两个参数,都是python本身定义的,默认就行了。
def application(environ, start_response):
    # 定义文件请求的类型和当前请求成功的code
    start_response('200 OK', [('Content-Type', 'application/json')])
    #request_body = environ["wsgi.input"].read(int(environ.get("CONTENT_LENGTH", 0)))   #post请求
    request_body = environ["QUERY_STRING"]   #get请求
    d = parse_qs(request_body)

    ip = d.get('ip', [''])[0]
    mask = d.get('mask', [''])[0]
    gateway = d.get('gateway', [''])[0]
    dns1 = d.get('dns1', [''])[0]
    dns2 = d.get('dns2', [''])[0]
    callback = d.get('callback', [''])[0]
    dic = {'ip': ip, 'mask': mask,'gateway':gateway,'dns1':dns1,'dns2':dns2}

    res = {'success':1,'message':'成功!'}
    for key,value in dic.items() :
        if not re.match("\d{1,3}(?:\.\d{1,3}){3}",value) :
            res['success'] = 0;
            res['message'] = 'ip格式错误';
            return HttpResponse(callback + "(" + json.dumps(res) + ")")

    if dic['ip'][0:dic['ip'].rfind('.')] != dic['gateway'][0:dic['ip'].rfind('.')] :
        res['success'] = 0;
        res['message'] = 'ip格式错误';
        return HttpResponse(callback + "(" + json.dumps(res) + ")")

    #设置ip
    os.system("sh changeIP.sh {} {} {} {} {}".format(ip,mask,gateway,dns1,dns2))
   #jsonp
    return HttpResponse(callback + "(" + json.dumps(res) + ")")

if __name__ == "__main__":
    port = 11112
    httpd = make_server("0.0.0.0", port, application)
    print "serving http on port {0}...".format(str(port))
    httpd.serve_forever()

 

posted @ 2019-03-04 17:45  zhang-san  阅读(318)  评论(0编辑  收藏  举报