Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在一个简单的wsgi应用程序中响应ajax?_Python_Ajax_Wsgi - Fatal编程技术网

Python 如何在一个简单的wsgi应用程序中响应ajax?

Python 如何在一个简单的wsgi应用程序中响应ajax?,python,ajax,wsgi,Python,Ajax,Wsgi,出于培训目的,我尝试制作一个简单的wsgi应用程序,需要一些问题的帮助。提前感谢所有回答的人 我有以下代码: from wsgiref.simple_server import make_server import re def collectTemplate(body): header_html = open('templates/header.html', encoding='utf-8').read() footer_html = open('templates/foo

出于培训目的,我尝试制作一个简单的wsgi应用程序,需要一些问题的帮助。提前感谢所有回答的人
我有以下代码:

from wsgiref.simple_server import make_server
import re


def collectTemplate(body):
    header_html = open('templates/header.html', encoding='utf-8').read()
    footer_html = open('templates/footer.html', encoding='utf-8').read()
    html = header_html + body + footer_html
    return html.encode('utf-8')

def indexPage(environ, start_response):
    path = environ.get('PATH_INFO')
    print(path)
    status = '200 OK'
    headers = [("Content-type", "text/html; charset=utf-8")]
    start_response(status, headers)
    body = """
        <h1>Hello index</h1>
        <div class='send'>Send ajax</div>
        <script>
            $('.sjd').on('click', function(){
                $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    data: {'data': 'hello'},
                    url: 'ajax.py',
                    success: function (msg) {
                        console.log(msg)
                    },
                    error : function (msg){
                        console.log(msg)
                    }
                });
            });
        </script
        """
    html = collectTemplate(body)
    return [html.encode('utf-8')]

def anotherPage(environ, start_response):
    status = '200 OK'
    headers = [("Content-type", "text/html; charset=utf-8")]
    start_response(status, headers)
    body = "<h1>Hello another page</h1>"
    html = collectTemplate(body)
    return [html.encode('utf-8')]

def page404(environ, start_response):
    start_response('404 NOT FOUND', [('Content-Type', 'text/html')])
    return ['Not Found']

urls = [
    (r'^$', indexPage),
    (r'another/?$', anotherPage),
]

def application(environ, start_response):
    path = environ.get('PATH_INFO', '').lstrip('/')
    for regex, callback in urls:
        match = re.search(regex, path)
        if match is not None:
            environ['url_args'] = match.groups()
            return callback(environ, start_response)
    return page404(environ, start_response)

if __name__ == '__main__':
    srv = make_server('', 8000, application)
    srv.serve_forever()
问题2)当您开始切换时,有两个页面(127.0.0.1:8000)和(127.0.0.1:8000/另一个/),当您切换所有内容时,控制台收到错误。为什么会这样

File "C:\Python\Python37-32\lib\wsgiref\simple_server.py", line 35, in close
self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'

AJAX请求与任何其他请求都很相似,只是您经常返回数据、部分模板或文件。要为AJAX请求创建端点,只需执行与之前相同的操作。创建一个函数并将该函数添加为端点。从传入标记的url中删除
.py
扩展名

导入cgi
def handle_ajax(环境,启动响应):
存储=cgi.FieldStorage()
data=storage.getvalue('data')
打印('状态:200正常')
打印('内容类型:文本/普通')
打印(“”)
如果数据不是无:
打印(数据)
URL[…,(r'ajax',handle_ajax)]

至于你的第二个问题,这真的很奇怪。它看起来很像
self.status
是None,即使它应该设置为您传入
start\u response
status
。你能用更多的stacktrace来扩展你的问题吗?另外,请尝试传递命名参数
start\u response(status=status,headers=headers)

谢谢您给我们发送了正确的路径,解决方案如下所示

 def ajax(environ, start_response): 
        start_response('200 OK', [('Content-Type', 'text/json')])
        json_string = json.dumps({'status':'ok'})
        return [json_string.encode()]

当您尝试发出ajax请求时,在控制台浏览器中获取“net::ERR_EMPTY_RESPONSE”。可能函数“handle\u ajax”没有正确执行。如何理解问题是什么?如何在Python中看起来像ajax的必要响应?您不会返回值,这是真的。Ajax请求通常做两件事中的一件:它们从服务器获取一个值,因此有一个返回值;或者它们在服务器上存储/更新某些内容,并需要返回成功发生的情况。在这种情况下,他们需要返回一条状态消息。类似于
start_响应('200ok',[('Content-Type','text/json'));返回{'message':'datastoragesuccessfully'}
应该足够了
 def ajax(environ, start_response): 
        start_response('200 OK', [('Content-Type', 'text/json')])
        json_string = json.dumps({'status':'ok'})
        return [json_string.encode()]