Book Image

Python Programming Blueprints

By : Daniel Furtado, Marcus Pennington
Book Image

Python Programming Blueprints

By: Daniel Furtado, Marcus Pennington

Overview of this book

Python is a very powerful, high-level, object-oriented programming language. It's known for its simplicity and huge community support. Python Programming Blueprints will help you build useful, real-world applications using Python. In this book, we will cover some of the most common tasks that Python developers face on a daily basis, including performance optimization and making web applications more secure. We will familiarize ourselves with the associated software stack and master asynchronous features in Python. We will build a weather application using command-line parsing. We will then move on to create a Spotify remote control where we'll use OAuth and the Spotify Web API. The next project will cover reactive extensions by teaching you how to cast votes on Twitter the Python way. We will also focus on web development by using the famous Django framework to create an online game store. We will then create a web-based messenger using the new Nameko microservice framework. We will cover topics like authenticating users and, storing messages in Redis. By the end of the book, you will have gained hands-on experience in coding with Python.
Table of Contents (17 chapters)
Title Page
Copyright and Credits
Dedication
Contributors
Packt Upsell
Preface
Index

Browser polling for messages


When the browser makes a poll to get the latest messages, our server should return the messages in a JSON format. To achieve this, we'll need to create a new HTTP endpoint that returns the messages as JSON, without using the Jinja2 templating. We will first construct a new helper function to create a JSON response, setting the correct headers.

Outside of our WebServer, create the following function:

def create_json_response(content): 
    headers = {'Content-Type': 'application/json'} 
    json_data = json.dumps(content) 
    return Response(json_data, status=200, headers=headers) 

This is similar to our create_html_response from earlier, but here it sets the Content-Type to 'application/json' and converts our data into a valid JSON object.

Now, within the WebServer, create the following HTTP entrypoint:

@http('GET', '/messages') 
def get_messages(self, request): 
    messages = self.message_service.get_all_messages() 
    return create_json_response(messages) 

This...