首页 > 解决方案 > 如何在一个简单的 wsgi 应用程序中响应 ajax?

问题描述

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

标签: pythonajaxwsgi

解决方案


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

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.statusis None,即使它应该设置为statusyou pass in start_response。你能用更多的堆栈跟踪来扩展你的问题吗?另外,也许尝试传递命名参数start_response(status=status, headers=headers)


推荐阅读