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

How to respond to ajax in a simple wsgi app?

出于培训目的,我尝试制作一个简单的 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()

问题1)最重要的是如何实现ajax并作答呢? 我将非常感谢示例。我在 ajax.py 中尝试了以下代码,但没有结果

import cgi
storage = cgi.FieldStorage()
data = storage.getvalue('data')
print('Status: 200 OK')
print('Content-Type: text/plain')
print('')
if data is not None:
    print(data)

问题2)启动时有两个页面(127.0.0.1:8000)和(127.0.0.1:8000/another/)切换时一切正常,但控制台出现错误。为什么会这样?

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 请求就像任何其他请求一样,只是您经常 return 数据、部分模板或文件。要为 AJAX 请求创建端点,只需执行与之前相同的操作即可。创建一个函数并将该函数添加为端点。从您传入标记的 url 中删除 .py 扩展名。

import cgi

def handle_ajax(environ, start_response):
  storage = cgi.FieldStorage()
  data = storage.getvalue('data')
  print('Status: 200 OK')
  print('Content-Type: text/plain')
  print('')
  if data is not None:
    print(data)


urls [..., (r'ajax', handle_ajax)]

关于你的第二个问题,这真的很奇怪。它看起来很像 self.status 是 None,即使它应该设置为您在 start_response 中传递的 status。你能用更多的堆栈跟踪来扩展你的问题吗?另外,也许尝试传递命名参数 start_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()]