Python Falcon – Discussion

Discuss Python Falcon ”; Previous Next Falcon is a Python library for developing mission-critical REST APIs and microservices. It supports both WSGI and ASGI specifications. Falcon framework has been developed by Kurt Griffiths in January 2013. The latest version of Falcon is 3.1.0, released in March 2022. Print Page Previous Next Advertisements ”;

Python Falcon – API Testing Tools

Python Falcon – API Testing Tools ”; Previous Next Falcon is a minimalistic framework suitable for developing APIs. An API is an interface between two applications. The API developer needs to test its functionality, reliability, stability, scalability, and performance etc. before releasing it for use in production environment. Various API testing tools are available for this purpose. In this section, we shall learn how to use command line tools Curl and HTTPie, and a GUI tool called Postman. cURL cURL is an open source project that provides libcurl library and a command line tool called curl that enables transferring data using various protocols. More than 20 protocols including HTTP are supported. The acronym cURL stands for Client URL. The syntax for using Curl from command line is − curl [options] [URL1, URL2,..] The URL parameter consists of protocol dependent, one or more URL strings. The Curl command can be customized with various options. Some of the important command line options are as follows − – X: Mention the request method. By default, Curl assumes GET to be the request method. To send POST, PUT or DELTETE requests, this option must be used. For example − Curl –X DELETE http://localhost:8000/student/1 – H: This option is used to add headers in the request. For example − Curl –H “Content-Type: application/json” -X GET http://localhost:8000/students – i: When this option is included in the command line, all the response headers are displayed. For example − Curl –I –X DELETE http://localhost:8000/student/2 – d: To include data in the HTTP request for processing, we have to use this option, particularly when POST or PUT request is needed. Curl –H “Content-Type: application/json” -X PUT -d “{“””marks”””:”””50″””}” http://localhost:8000/students/3 HTTPie The HTTPie is a command line tool written in Python. It is said to be a “cURLlike tool for humans”. It supports forms and file uploads and generates nicely formatted colorized terminal output. Its expressive and intuitive syntax makes it easier to use as compared to Curl. Examples GET request − http GET localhost:8000/students POST request − http POST localhost:8000/students id=4 name=”aaa” percent=50 PUT request − http PUT localhost:8000/students/2 id=3 name=”Mathews” percent=55 DEETE request − http DELETE localhost:8000/students/2 Postman Postman is a very popular API testing tool. It is a GUI app as against Curl and HTTPie. It is available in the form of a browser plugin as well as a desktop application. As the browser plugin doesn”t accept requests for localhost based APIs, we need to download the desktop version from https://www.postman.com/downloads. After completing the wizard based installation, start the Postman app and create a new request. The dropdown shows various HTTP request types to choose from. Enter http://localhost:8000/hello in the request URL field. The response pane on the right shows the result. We shall use the corresponding request types later when we test the Falcon API for CRUD operations on a SQLite database. Print Page Previous Next Advertisements ”;

Python Falcon – Useful Resources

Python Falcon – Useful Resources ”; Previous Next The following resources contain additional information on Python Falcon. Please use them to get more in-depth knowledge on this. Useful Links on Python Falcon Python Falcon − Official Website of Python Falcon Python Falcon Wiki − Wikipedia Reference for Python Falcon Useful Books on Python Falcon To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

Python Falcon – Cookies

Python Falcon – Cookies ”; Previous Next A cookie is stored on a client”s computer in the form of a text file. Its purpose is to remember and track data pertaining to a client”s usage for better visitor experience and site statistics. A Request object contains a cookie”s attribute. It is a dictionary object of all the cookie variables and their corresponding values, a client has transmitted. In addition to it, a cookie also stores its expiry time, path and domain name of the site. In Falcon, cookies are set on response object using set_cookie() method. resp.set_cookie(”cookiename”, ”cookievalue”) Additionally, the arguments max_age of cookie in seconds and domain name can also be given. import falcon import json from waitress import serve class resource1: def on_post(self, req, resp): resp.set_cookie(“user”, ”admin”) resp.text = “cookie set successfully.” resp.status = falcon.HTTP_OK resp.content_type = falcon.MEDIA_TEXT From the command line, invoke the responder method as − http POST localhost:8000/cookie HTTP/1.1 200 OK Content-Length: 24 Content-Type: text/plain; charset=utf-8 Date: Tue, 26 Apr 2022 06:56:30 GMT Server: waitress Set-Cookie: user=admin; HttpOnly; Secure cookie set successfully. The cookie Set-cookie header can also be set using append_header() method of response object. To retrieve the cookies, the request object has request.cookies property as well as get_cookie_values() method. def on_get(self, req, resp): cookies=req.cookies values = req.get_cookie_values(”user”) if values: v = values[0] resp.body={“user”:v} resp.status = falcon.HTTP_OK resp.content_type = falcon.MEDIA_JSON The unset_cookie method of response object clears the cookie for the current request. resp.unset_cookie(”user”) For ASGI applications, falcon.asgi.Request implements the same cookie methods and properties as falcon.Request. The ASGI versions of set_cookie() and append_header() are synchronous, so they do not need to be awaited. Print Page Previous Next Advertisements ”;

Python Falcon – Quick Guide

Python Falcon – Quick Guide ”; Previous Next Python Falcon – Introduction Falcon is a Python library for developing mission-critical REST APIs and microservices. It supports both WSGI and ASGI specifications. Falcon framework has been developed by Kurt Griffiths in Jan. 2013. The latest version of Falcon is 3.1.0, released in March 2022. Falcon is a lightweight web development framework. Its minimalist design allows the developer to select the best strategies and 3rd-party packages as required. Falcon – Important Features Falcon is released under the terms of the Apache 2.0 License. Some of the important features of Falcon include − Latest version of Falcon supports ASGI, WSGI, as well as WebSocket. Falcon provides native support for asyncio. Its stable interfaces ensure backwards-compatibility Falcon follows REST architectural style for building APIs. Class based construction of HTTP resources. Highly-optimized, extensible code base. Falcon provides easy access to headers and bodies through request and response classes Middleware components and hooks available for DRY request processing. Idiomatic HTTP error responses and exception handling. Falcon – Design Philosophy Falcon minimizes the instantiation of number of objects so as to avoid the expense of creating the object, and to reduce memory usage. The same instance will be used to serve all requests coming in on that route. Exceptions are properly handled by the resource responders (methods such as on_get(), on_post(), etc.). Falcon doesn”t try very hard to protect responder code from itself. A high-quality Falcon API should fulfil following requirements − Resource responders set response variables to sane values. Your code is well-tested, with high code coverage. Custom error handlers are provided within each responder to anticipate, detect, and handle errors. The Falcon framework is thread-safe. Separate new Request and Response objects are created for each incoming HTTP request. However, a single instance of each resource class attached to a route is shared among all requests. Middleware objects, hooks, and custom error handlers, are also shared. Therefore, your WSGI app as a whole will be thread-safe. Starting with version 3.0, Falcon supports asyncio. Use the falcon.asgi.App class to create an async application, and serve it via an ASGI application server such as Uvicorn. The async version of Falcon supports the ASGI WebSocket protocol. Falcon – Comparison with Other Frameworks There are two major categories of Python web frameworks − full-stack and micro frameworks. Full-stack frameworks come with built-in features and libraries. Django, Turbogears, and Web2Py are full-stack frameworks. In contrast, micro-frameworks are minimalistic, only providing the bare minimum; thus gives developers the freedom to choose official or third-party extensions and only include plugins which they need. Flask, Falcon, Pyramid belong to micro framework category. We compare Falcon framework against different frameworks on the basis of the following parameters − Performance Falcon application is very fast, in comparison with micro frameworks such as Flask and pyramid. The full stack frameworks are generally slow. REST Support Falcon is intended to be a framework of choice for development of REST APIs and microservices. FastAPI also encourages REST development. Flask and Django don”t have built-in REST support. However, it can be enabled using extensions. Templating Falcon app is not supposed to serve template web pages. It is not bundled with any templating library. However, one can use jinja2 or Macho libraries. On the other hand, Flask has a built-in support for jinja2. Django has its own templating library. FastAPI also can handle any template library of choice. Database Support In Falcon database support is not built-in. It is possible to use SQLAlchemy models to interact with relational databases like MyQL, PostgreSQL, SQLite etc. Django on the other hand has its own ORM framework for use out of the box. A Flask application also can interact with databases through Flask extensions. Earlier versions of TurboGears had compatibility with SQLObject ORM library. The newer version is compatible with SQLAlchemy. Flexibility Falcon applications are very flexible. It is ideal for applications that require a high degree of customization and performance tuning. FastAPI and Flask too are flexible to code and doesn”t restrict users to a particular project or code layout. Security Falcon has no built-in support to ensure security. Other frameworks like Django and FastAPI ensure high degree of security. Flask also provides excellent protection against security threats such as CSRF and XSS attacks. Testing Falcon offers built-in testing support using unittest and Pytest. Flask and Django also supports unittest. FastAPI supports unittest and starlette testing features. Python Falcon – Environment Setup The latest version of Falcon requires Python 3.5 or newer version. The easiest as well as recommended way to install Falcon is with PIP installer, preferably in a virtual environment. The latest stable version can be installed by running the following command − pip3 install falcon To verify if the installation has been performed successfully, import the library and check its version. >>> import falcon >>>falcon.__version__ ”3.1.0” To install the latest beta version, following command should be used − pip3 install –pre falcon Right from the early version, Falcon supports WSGI. A Falcon app can be run with the help of built-in WSGI server in Python”s standard library module wsgiref. However, it is not suitable for production environment, for which WSGI servers such as gunicorn, waitress or uwsgi are required. For Falcon on Windows, one can use Waitress, a production-quality, pure-Python WSGI server. As usual, install it with pip installer. pip3 install waitress The Gunicorn server can”t be installed on Windows. However, it can be used inside a Windows Subsystem Linux (WSL) environment on Windows 10. For using gunicorn on Linux, WSL or inside Docker containers, use

Python Falcon – Waitress

Python Falcon – Waitress ”; Previous Next The development server is not recommended to be used in production environment. The development server is not efficient, stable, or secure. Waitress is a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones that live in the Python standard library. It runs on CPython on Unix and Windows. Make sure that Waitress server has been installed in the working environment. The library contains serve class whose object is responsible for serving the incoming requests. The constructor of serve class requires three parameters. serve (app, host, port) The falcon application object is the app parameter. The default values of host and port are localhost 8080 by default. The listen parameter is a string as a combination of host:port parameter defaulting to ”0.0.0.0:8080” Example In the hellofalcon.py code, we import the serve class instead of simple_server and instantiate its object as follows − from waitress import serve import falcon 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” ) app = falcon.App() hello = HelloResource() app.add_route(”/hello”, hello) if __name__ == ”__main__”: serve(app, host=”0.0.0.0”, port=8000) Execute hellofalcon.py and visit the http://localhost:8000/hellolink in the browser as before. Note that the host 0.0.0.0 makes the localhost publicly visible. The Waitress server can be launched from the command line also, as shown below − waitress-serve –port=8000 hellofalcon:app Print Page Previous Next Advertisements ”;

Python Falcon – App Class

Python Falcon – App Class ”; Previous Next This class is the main entry point into a Falcon-based WSGI app. An instance of this class provides a callable WSGI interface and a routing engine. import falcon app = falcon.App() The __init__() constructor of this class takes the following keyword arguments − media_type − media type to use when initializing RequestOptions and ResponseOptions. Falcon allows for easy and customizable internet media type handling. By default, Falcon only enables handlers for JSON and HTML (URL-encoded and multipart) forms. Other media types supported by Falcon are represented by the following constants − falcon.MEDIA_JSON falcon.MEDIA_MSGPACK falcon.MEDIA_MULTIPART falcon.MEDIA_URLENCODED falcon.MEDIA_YAML falcon.MEDIA_XML falcon.MEDIA_HTML falcon.MEDIA_JS falcon.MEDIA_TEXT falcon.MEDIA_JPEG falcon.MEDIA_PNG falcon.MEDIA_GIF request_type − Default value of this argument is falcon.Request class. response_type − Default value of this argument is falcon.Response class. In order to make the App object callable, its class has a __call__() method. __call__(self, env, start_response) This is a WSGI app method. The WSGI development server or other production servers (Waitress/Uvicorn) use this object to launch the server instance and listen to the requests from the client. The App class also defines the add_route() method. add_route(self, uri_template, resource) This method helps in associating a URI path with an object of resource class. Incoming requests are routed to resources based on a set of URI templates. If the path matches the template for a given route, the request is then passed on to the associated resource for processing. Depending on the request method, the respective responder methods are called. Example Let us add on_post() responder method to HelloResource class and test the endpoints for GET as well as POST requests. from waitress import serve import falcon import json class HelloResource: def on_get(self, req, resp): resp.status = falcon.HTTP_200 resp.content_type = falcon.MEDIA_TEXT resp.text = ( ”Hello World” ) def on_post(self, req, resp): data=req.media nm=data[”name”] resp.status = falcon.HTTP_200 resp.content_type = falcon.MEDIA_TEXT resp.text = ( ”Hello ”+nm ) app = falcon.App() hello = HelloResource() app.add_route(”/hello”, hello) if __name__ == ”__main__”: serve(app, host=”0.0.0.0”, port=8000) Output Run the application using Waitress server and check the responses using Curl. For response to GET request, using following command − C:UsersUser>curl localhost:8000/hello Hello World We send some data to the /hello URL by POST method as follows − C:UsersUser>curl -i -H “Content-Type:application/json” -X POST -d “{“””name”””:”””John”””}” http://localhost:8000/hello HTTP/1.1 200 OK Content-Length: 10 Content-Type: text/plain; charset=utf-8 Date: Sun, 17 Apr 2022 07:06:20 GMT Server: waitress Hello John To add a route to a directory of static files, Falcon has add_static_route() method. add_static_route(self, prefix, directory, downloadable=False, fallback_filename=None) The prefix argument is the path prefix to match for this route. The directory argument is the source directory from which to serve files. The downloadable argument is set to True if you want to include a ContentDisposition header in the response. The fallback_filename is by default None but can be specified when the requested file is not found. The add_error_handler() method is used to register a handler for one or more exception types. add_error_handler(self, exception, handler=None) The ASGI callable App class possesses the same methods. It is defined in falcon.asgi module. import falcon.asgi app=falcon.asgi.App() Note that the responders of the resource class in an ASGI application must be coroutines (defined with async keyword) instead of normal methods. class HelloResource: async def on_get(self, req, resp): “””Handles GET requests””” resp.status = falcon.HTTP_200 resp.content_type = falcon.MEDIA_TEXT resp.text = ( ”Hello World” ) Print Page Previous Next Advertisements ”;

Python Falcon – Uvicorn

Python Falcon – Uvicorn ”; Previous Next Uvicorn uses uvloop and httptools libraries. It also provides support for HTTP/2 and WebSockets, which cannot be handled by WSGI. uvloop is similar to the built-in asyncio event loop. httptools library handles the http protocols. Falcon”s ASGI compliant application is launched on Uvicorn server with following command − Uvicorn hellofalcon:app – reload The –reload option enables the debug mode, so that any changes in app.py will be automatically reflected and the display on the client browser will be automatically refreshed. In addition, the following command-line options may be used − –host TEXT Bind socket to this host. [default 127.0.0.1] –port INTEGER Bind socket to this port. [default 8000] –uds TEXT Bind to a UNIX domain socket. –fd INTEGER Bind to socket from this file descriptor. –reload Enable auto-reload. –reload-dir PATH Set reload directories explicitly, default current working directory. –reload-include TEXT Include files while watching. Includes ”*.py” by default –reload-exclude TEXT Exclude while watching for files. –reload-delay FLOAT Delay between previous and next check default 0.25 –loop [auto|asyncio|uvloop] Event loop implementation. [default auto] –http [auto|h11|httptools] HTTP protocol implementation. [default auto] –interface auto|asgi|wsgi Select application interface. [default auto] –env-file PATH Environment configuration file. –log-config PATH Logging configuration file. Supported formats .ini, .json, .yaml. –version Display the Uvicorn version and exit. –app-dir TEXT Look for APP in the specified directory default current directory –help Show this message and exit. The Uvicorn server can also be launched from within the program instead of the above command line. To do that, import uvicorn module and call uvicorn.run() method as shown below − import uvicorn if __name__ == “__main__”: uvicorn.run(“hellofalcon:app”, host=”0.0.0.0″, port=8000, reload=True) Change the hellofalcon.py code accordingly, and execute the same from command prompt. The result can be verified by the curl command or in the browser as explained earlier. Print Page Previous Next Advertisements ”;

Python Falcon – Environment Setup

Python Falcon – Environment Setup ”; Previous Next The latest version of Falcon requires Python 3.5 or newer version. The easiest as well as recommended way to install Falcon is with PIP installer, preferably in a virtual environment. The latest stable version can be installed by running the following command − pip3 install falcon To verify if the installation has been performed successfully, import the library and check its version. >>> import falcon >>>falcon.__version__ ”3.1.0” To install the latest beta version, following command should be used − pip3 install –pre falcon Right from the early version, Falcon supports WSGI. A Falcon app can be run with the help of built-in WSGI server in Python”s standard library module wsgiref. However, it is not suitable for production environment, for which WSGI servers such as gunicorn, waitress or uwsgi are required. For Falcon on Windows, one can use Waitress, a production-quality, pure-Python WSGI server. As usual, install it with pip installer. pip3 install waitress The Gunicorn server can”t be installed on Windows. However, it can be used inside a Windows Subsystem Linux (WSL) environment on Windows 10. For using gunicorn on Linux, WSL or inside Docker containers, use pip3 install gunicorn If you want to run an asynchronous Falcon app, an ASGI compliant application server is required. The Uvicorn server can be used on Windows as well as Linux systems. pip3 install uvicorn Print Page Previous Next Advertisements ”;

Python Falcon – Jinja2 Template

Python Falcon – Jinja2 Template ”; Previous Next The Falcon library is primarily used to build APIs and microservices. Hence, by default, a Falcon responder returns a JSON response. However, if the content type is changed to falcon.MEDIA_HTML, it is possible to render HTML output. Rendering a HTML content with variable data is very tedious. For this purpose, web templating libraries are used. Many Python web frameworks are bundled with specific template library. But Falcon being a minimalist micro framework doesn”t come pre-bundled with anyone. Jinja2 is one of the most popular template libraries used by many python frameworks. In this section, we shall see how to use inja2 with Falcon application. The jinja2 is a fast and designer-friendly templating language that is easy to configure and debug. Its sandboxed environment makes it easy to prevent the execution of untrusted code, prohibit potentially unsafe data, and prevent cross-site scripting attacks (called XSS attacks). Another very powerful feature of jinja2 is the template inheritance, wherein You can define a base template having common design features which child templates can override. First of all, install jinja2 in the current Python environment with the use of PIP utility. pip3 install jinja2 Hello World Template The jinja2 module defines a Template class. A Template object is obtained by reading the contents of a file containing HTML script (one with .html extension). By invoking the render() method of this Template object, HTML response can be rendered to the client browser. The content_type property of Response object must be set to falcon.MEDIA_HTML. Let us save the following HTML script as hello.py in the application folder. <html> <body> <h2>Hello World</h2> </body> </html> Example The on_get() responder in the resource class below reads this file and renders it as HTML response. import uvicorn import falcon import falcon.asgi from jinja2 import Template class HelloResource: async def on_get(self, req, resp): resp.status = falcon.HTTP_200 resp.content_type = ”text/html” fp=open(“hello.html”,”r”) tempobj=Template(fp.read()) resp.body=tempobj.render() app = falcon.asgi.App() hello = HelloResource() app.add_route(”/hello”, hello) if __name__ == “__main__”: uvicorn.run(“hello:app”, host=”0.0.0.0″, port=8000, reload=True) Output Run the above Python code and visit http://localhost:8000/hello link in the browser. Template Variable jinja2 is a server-side templating library. The web page is constructed as a template by putting various elements of jinja2 templating language as place-holders within appropriate delimiters inside the HTML script. The template engine reads the HTML script, substitutes the place-holders with context data on the server, reassembles the HTML, and renders it to the client. The Template.render() function has an optional context dictionary parameter. The key attributes of this dictionary become the template variables. This helps in rendering the data passed by the responders in the web page. Example In the following example, the route /hello/nm is registered with the resource object, where nm is the path parameter. The on_get() responder passes it as a context to the template object obtained from a web page. import uvicorn import falcon import falcon.asgi from jinja2 import Template class HelloResource: async def on_get(self, req, resp, nm): resp.status = falcon.HTTP_200 resp.content_type = ”text/html” fp=open(“hello.html”,”r”) tempobj=Template(fp.read()) resp.body=tempobj.render({”name”:nm}) app = falcon.asgi.App() hello = HelloResource() app.add_route(”/hello/{nm}”, hello) if __name__ == “__main__”: uvicorn.run(“hello:app”, host=”0.0.0.0″, port=8000, reload=True) The hello.html reads the path parameter in a template variable name. It acts as a place holder in the HTML script. It is put in {{ and }} symbols so that its value appears as a HTML response. <html> <body> <h2>Hello {{ name }}</h2> </body> </html> Output Run the Python code and enter http://localhost:8000/hello/Priya as the URL. The browser displays the following output − Loop in jinja2 Template If the responder passes any Python iterable object such as a list, tuple or a dictionary, its elements can be traversed inside the jinja2 template using its looping construct syntax. {% for item in collection %} HTML block {% endfor %} In the following example, the on_get() responder sends students object which is a list of dict objects, to the template list.html. It in turn traverses the data and renders it as a HTML table. import falcon import json from waitress import serve from jinja2 import Template students = [ {“id”: 1, “name”: “Ravi”, “percent”: 75.50}, {“id”: 2, “name”: “Mona”, “percent”: 80.00}, {“id”: 3, “name”: “Mathews”, “percent”: 65.25}, ] class StudentResource: def on_get(self, req, resp): resp.status = falcon.HTTP_OK resp.content_type = falcon.MEDIA_HTML fp=open(“list.html”,”r”) tempobj=Template(fp.read()) resp.body=tempobj.render({”students”:students}) list.html is a jinja2 template. It receives the students object as list of dictionary objects and puts the value of each key inside <td>..<.td> element of a table. <html> <body> <table border=1> <thead> <tr> <th>Student ID</th> <th>Student Name</th> <th>percentage</th> <th>Actions</th> </tr> </thead> <tbody> {% for Student in students %} <tr> <td>{{ Student.id }}</td> <td>{{ Student.name }}</td> <td>{{ Student.percent }}</td> <td> <a href=”#”>Edit</a> <a href=”#”>Delete</a> </td> </tr> {% endfor %} </tbody> </table> </body> </html> Visit the /students route in the browser”s address bar. The list of students is rendered in the browser. HTML Form Template In this section, we shall see how Falcon reads the data from HTML form. Let us save the following HTML script as myform.html. We shall use it for obtaining Template object and render it. <html> <body> <form method=”POST” action=”http://localhost:8000/students”> <p>Student Id: <input type=”text” name=”id”/> </p> <p>student Name: <input type=”text” name=”name”/> </p> <p>Percentage: <input type=”text” name=”percent”/> </p> <p><input type=”submit”> </p> </body> </html> The Falcon App object is declared in Hello.py file which also has a resource class mapped to /adddnew route. The on_get() responder reads the myform.html and renders the same. The HTML form will be displayed. The form is submitted to /students route by POST method. To be able to read the form data, the auto_parse_form_urlencoded property of falcon.RequestOptions class must be set to True. app = falcon.App() app.req_options.auto_parse_form_urlencoded = True Here, we also import StudentResource