如何在简单的wsgi应用程序中响应Ajax?

时间:2019-07-02 09:26:01

标签: 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/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'

2 个答案:

答案 0 :(得分:1)

AJAX请求与其他任何请求一样,只是您经常返回数据,部分模板或文件。要为AJAX请求创建端点,只需完成与之前相同的操作即可。创建一个函数并将该函数添加为端点。从您在标记中传递的网址中删除.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设置为您传入status的{​​{1}},但看起来好像start_response是None。您可以使用更多的stacktrace扩展您的问题吗?另外,也许尝试传递命名参数start_response(status=status, headers=headers)

答案 1 :(得分:0)

感谢您以正确的方式发送给我们,解决方案如下所示

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