English 中文(简体)
Python Falcon - Hello World(WSGI)
  • 时间:2024-09-17

Python Falcon - Hello World(WSGI)


Previous Page Next Page  

To create a simple Hello World Falcon app, start with importing the pbrary and declaring an instance of App object.


import falcon
app = falcon.App()

Falcon follows REST architectural style. Declare a resource class that includes one or more methods representing the standard HTTP verbs. The following HelloResource class contains on_get() method that is expected to get called when the server receives GET request. The method returns Hello World response.


class HelloResource:
   def on_get(self, req, resp):
   """Handles GET requests"""
   resp.status = falcon.HTTP_200
   resp.content_type = falcon.MEDIA_TEXT
   resp.text = (
       Hello World 
   )

To invoke this method, we need to register it to a route or URL. The Falcon apppcation object handles the incoming requests by assigning the handler methods to corresponding URLs by add_rule method.


hello = HelloResource()
app.add_route( /hello , hello)

The Falcon apppcation object is nothing but a WSGI apppcation. We can use the built-in WSGI server in the wsgiref module of Python s standard pbrary.


from wsgiref.simple_server import make_server

if __name__ ==  __main__ :
   with make_server(  , 8000, app) as httpd:
   print( Serving on port 8000... )
# Serve until process is killed
httpd.serve_forever()

Example

Let us put all these code fragments in hellofalcon.py


from wsgiref.simple_server import make_server

import falcon

app = falcon.App()

class HelloResource:
   def on_get(self, req, resp):
      """Handles GET requests"""
      resp.status = falcon.HTTP_200
      resp.content_type = falcon.MEDIA_TEXT
      resp.text = (
          Hello World 
      )
hello = HelloResource()

app.add_route( /hello , hello)

if __name__ ==  __main__ :
   with make_server(  , 8000, app) as httpd:
   print( Serving on port 8000... )
# Serve until process is killed
httpd.serve_forever()

Run this code from the command prompt.


(falconenv) E:falconenv>python hellofalcon.py
Serving on port 8000...

Output

In another terminal, run the Curl command as follows −


C:Usersuser>curl localhost:8000/hello
Hello World

You can also open a browser window and enter the above URL to obtain the "Hello World" response.

Python Falcon Hello World Advertisements