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

Sending messages via POST requests


So far we've made good progress; we have a site that has the ability to display all of the messages in our data store with two microservices. One microservice handles the storing and retrieval of our messages, and the other acts as a web server for our users. Our MessageService already has the ability to save messages; let's expose that in our WebServer via a POST request.

Adding a send messages POST request

In our service.py, add the following import:

import json 

Now add the following to our WebServer class:

@http('POST', '/messages') 
def post_message(self, request): 
    data_as_text = request.get_data(as_text=True) 
 
    try: 
        data = json.loads(data_as_text) 
    except json.JSONDecodeError: 
        return 400, 'JSON payload expected' 
 
    try: 
        message = data['message'] 
    except KeyError: 
        return 400, 'No message given' 
 
    self.message_service.save_message(message) 
 
    return 204, '' 

With our new POST entrypoint, we...