How do I do URL Dispatch on Python?

Asked 2 years ago, Updated 2 years ago, 21 views

I'd like to do something API-like, but how can I implement URL Dispatch in Python without using large-scale frameworks such as Django?

python

2022-09-29 21:52

3 Answers

If it's URL-to-view mapping, what about WebDispatches?


2022-09-29 21:52

If you want to implement it yourself, I think you can create something that maps the values in PATH_INFO to the views you want to call.
If it's simple, it's like ↓.
https://github.com/heavenshell/py-autodoc/blob/master/tests/app.py#L36

Instead of just making these things yourself, I recommend using a library like Takayuki-shimizukawa wrote or something like WebOB or Werkzeug.
http://werkzeug.pocoo.org/docs/0.9/


2022-09-29 21:52

Python defines the API when a web server invokes a web application.If you follow this standard, you can run the same app on Apache or Nginx.This is called WSGI.WSGI's app is a function that takes two arguments: environ and start_response:

In order to do URL Dispatch, environ['PATH_INFO'] contains the path, so you just have to separate the cases according to this string and return each string.

def hello_world_app(environ, start_response):
    status='200 OK'#HTTPStatus
    headers = [('Content-type', 'text/plain')] # HTTP Headers

    # Now, make a response according to PATH_INFO.
    path_info=environ ['PATH_INFO' ]
    if path_info=='/':
       response='index!'
    elif path_info=='/secret':
       response='secret!'
    else:
        # Return 404 if not found
        start_response('404 not found', heads)
        return ['the page you looked for was not found']

    start_response (status, headers)
    return [response]

if__name__=='__main__':
    from wsgiref.simple_server import make_server
    httpd=make_server(',8000,hello_world_app)
    print "Serving on port8000..."

    # Serve until process is killed
    httpd.serve_forever()

Look at the link in @heavenshell's answer to support up to HTTP methods.


2022-09-29 21:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.