Skip to main content

Twisted Klein: Request Parameter

Request Parameter: What is it and why is it passed in?


You may have noticed the request argument which gets passed into every route function.  This variable is a Request object and serves a very important purpose of holding valuable request information.  Request objects have an abundance of functionality in them, which would be tedious to convey in such a short tutorial.  Some concepts, such as usage of Deferred and callbacks, are formally introduced in other posts.

Write to the Frontend


Content can slowly be added to the frontend using the Request.write() function.  Please note that the parameter must be a bytes type, Python 2.7 users don't have to worry as strings are bytes, however in Python 3, a string is NOT a bytes object.

@app.route('/write')
def gradualWrite(request):
    request.write(b'<h1>Header</h1>')
    request.write(b'<h2>Header</h2>')
    request.write(b'<h3>Header</h3>')
    request.write(b'<h4>Header</h4>')
    request.write(b'<h5>Header</h5>')


Getting Query String or Form Arguments


A common use case for any web application would be to handle form data or a query string.  The following will simply display all the form data or query string that's passed along.

@app.route('/args')
def arguments(request):
    return '{0}'.format(request.args)

Now lets test this route using GET with query strings and POST using form data.

curl -X GET curl -X GET localhost:9000/args?Eminem=Superman\&Hoozier=Church
curl -X POST -d Adele=Hello -d Adele="Fire to the Rain" localhost:9000/args

One thing that catches some by surprise the fact that argument values are in a list, even if there's only a single value.


Redirects


@app.route('/redirect')
def redirect(request):
    request.redirect('https://www.yahoo.com')

Finished Request


Execute a function after the request has finished using Request.notifyFinish().  This uses Deferred and callbacks.


import time

@app.route('/onfinish')
def onfinish(request):

    def displayTime(null, starttime):
        now = time.time()
        print('end - start time = {0}'.format(now-start))

    begintime = time.time()
    request.notifyFinish().addCallback(displayTime, begintime)
    return 'Request began at {0}'.format(begintime)

Cookies


@app.route('/cookies')
def cookies(request):
    value = request.args.get(b'cookie', [b'default'])
    request.addCookie('cookie', value[0])


Sessions


Get a Session object:


@app.route('/show')
def showSession(request):
    return b'Session id: ' + request.getSession().uid


Expire the session:


@app.route('/expire')
def expireSession(request):
    request.getSession().expire()
    return 'Session expired'

Test:

   curl -c _cookie.jar -b _cookie.jar localhost:9000/show
   curl -c _cookie.jar -b _cookie.jar localhost:9000/expire

Sessions can be a bit complex.  Read more about sessions at Twisted's site.

References



Comments

Popular posts from this blog

Twisted Klein: Non-Blocking Recipes

Non-Blocking Recipes Do you like expressjs , but don’t want to switch to Node.js? Want non-blocking execution in Python? Then look no further! Asynchronous execution is the very essence of what makes Klein a contender in todays web framework landscape. It’s also the most difficult concept to grasp since most Pythonistas are not accustomed to asynchronous programming. Hopefully with the addition asyncio to Python’s standard library, this will change. Klein is built atop Twisted and developers can expose Deferred objects for asynchronous behavior. A very brief overview will be given on Twisted Deferred , afterwards aspiring developers are encouraged to read the Twisted documents on the subject (provided in the links near the bottom). Deferred Overview To demonstrate how Deferred objects work, we will create a chain of callback functions that execute after a result is available. Don’t worry if this confuses you right now, the code will clear things up. from __future_...

Python alias commands that play nice with virtualenv

There are plenty of predefined Python executables, symlinks, and aliases that come bundled with your operating system. These commands come in very handy because it saves you from typing out long commands or chain of scripts. However the downfall of operating system aliases is that they don’t always play nice with virtualenv (or venv if you’re on Python 3). Most predefined aliases use the system’s default Python as the interpreter, which is next to useless when your application runs in a virtual environment. Over the years, I’ve come up with my own Python aliases that play nice with virtual environments. For this post, I tried to stay as generic as possible such that any alias here can be used by every Pythonista. In other words, there will be no aliases for specific frameworks such as running a Django server or starting a Scrappy spider. The following is one of my bash scripts I source: .py-aliases #----- Pip -----# alias pip-list="pip freeze | less" alias pip-search...

Simple self signed TLS server and client using Twisted

Self signed TLS server and client using Twisted Prerequisites openssl twisted & pyOpenSSL modules- pip install twisted[tls] treq module - pip install treq Basic knowledge of Twisted TCP servers/clients Generate self signed certificate Generate the server's private key using a secret, which is SuperSecretPassword in this case. openssl genrsa -aes256 -passout pass:SuperSecretPassword -out server.key 2048 Perform a CSR (certificate signing request). Ensure the FQDN (fully qualified domain name) matches the hostname of the server, otherwise the server won't be properly validated. openssl req -new -key server.key -passin pass:SuperSecretPassword -out server.csr # Common Name (e.g. server FQDN or YOUR name) []:localhost openssl x509 -req -passin pass:SuperSecretPassword -days 1024 -in server.csr -signkey server.key -out server.crt For development purposes, remove the password from the certificate. openssl rsa -in server.key -out server_no_pass.key -passin pas...