<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lance Goodridge on Medium]]></title>
        <description><![CDATA[Stories by Lance Goodridge on Medium]]></description>
        <link>https://medium.com/@ldgoodridge95?source=rss-c3e8f08beacc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aWnhXyrJEIpSMT3FBT8u8Q.jpeg</url>
            <title>Stories by Lance Goodridge on Medium</title>
            <link>https://medium.com/@ldgoodridge95?source=rss-c3e8f08beacc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:02:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ldgoodridge95/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Creating a Chat App with Serverless, Websockets, and Python: A Tutorial]]></title>
            <link>https://levelup.gitconnected.com/creating-a-chat-app-with-serverless-websockets-and-python-a-tutorial-54cbc432e4f?source=rss-c3e8f08beacc------2</link>
            <guid isPermaLink="false">https://medium.com/p/54cbc432e4f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[serverless-framework]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Lance Goodridge]]></dc:creator>
            <pubDate>Sun, 14 Apr 2019 01:06:08 GMT</pubDate>
            <atom:updated>2019-04-18T09:52:11.185Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a Chat App with Serverless, WebSockets, and Python: A Tutorial</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMp5eOUJthw-12RkPG3NBw.png" /></figure><p>Near the end of 2018, Amazon released support for <a href="https://aws.amazon.com/blogs/compute/announcing-websocket-apis-in-amazon-api-gateway/">WebSockets in API Gateway</a>, and recently, the Serverless framework <a href="https://serverless.com/blog/api-gateway-websockets-support/">has followed suit</a>. With WebSockets being directly supported by both of these tools, creating a real-time, bi-directional application is easier than ever before.</p><p>As of the writing of this article, there are a few tutorials on using WebSockets with Serverless, but none that use Python as the primary language, or fully describe building a serverless WebSocket application from start to finish: this article attempts to bridge that gap.</p><p>In this tutorial, we will build a canonical “chat” application that uses the <a href="https://serverless.com/">Serverless Framework</a> on top of AWS Lambda and API Gateway for the backend, along with a simple Django client. For good measure, we will use <a href="https://github.com/lgoodridge/django-uniauth/">django-uniauth</a> for authenticating users, and secure our requests with <a href="https://jwt.io/">JSON Web Tokens (JWT)</a>.</p><h3><strong>Step 1: Create an AWS User</strong></h3><p>The first thing we will do is create an AWS user to manage the app. You may alternatively use one you’ve already created, but having separate users for each application is marginally better for security (and organization).</p><p>Log into the <a href="https://console.aws.amazon.com/iam/home">IAM Management Console</a>, then go to Users, and click “Add user”. Give it a username, and be sure to check “Programmatic access” before continuing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aztLoqxaehn44jAAh6MtXQ.png" /></figure><p>Next, choose to “Attach existing policies directly”, and give the user “AdministratorAccess”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MRQOWyo45aqFjy7qATRDwQ.png" /></figure><p>We use this policy for simplicity, but for an actual application, you should select exactly the permissions you require.</p><p>Add tags to the user if you wish, otherwise, continue until the user is finally created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sQLJIWDk8dMa70GaJAlzhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVS-8Mb8uVqG8MrQM7xUpw.png" /></figure><p>Download the credentials CSV file and store it in a safe place, or at least take note of the Access Key and Secret Key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c272rOvHXtr8WXnS5USOEA.png" /></figure><p>Now add entry for it in ~/.aws/credentials</p><pre>[serverless-chat-tutorial]<br>aws_access_key_id = &lt;YOUR_ACCESS_KEY&gt;<br>aws_secret_access_key = &lt;YOUR_SECRET_KEY&gt;</pre><h3>Step 2: Install + Configure Serverless</h3><p>As with all Python projects, it’s a good idea to use a <a href="https://realpython.com/python-virtual-environments-a-primer/">virtual environment</a> to isolate our dependencies. Create a directory for the app:</p><pre>mkdir serverless-chat-tutorial<br>cd serverless-chat-tutorial</pre><p>Then create and activate a virtual environment:</p><pre>virtualenv -p python3 venv<br>. venv/bin/activate</pre><p>Now, lets install Serverless:</p><pre>sudo npm install -g serverless</pre><p>And export the necessary environment variables:</p><pre>export AWS_PROFILE=serverless-chat-tutorial<br>export AWS_REGION=us-east-1</pre><p>I like to setup my virtual environment to export these whenever the environment is activated, by adding these lines to the venv/bin/activate script.</p><h3>Step 3: Write a Serverless Ping function</h3><p>Let’s get our feet wet with the Serverless Framework by writing a simple “ping” function, that just echoes back a string to the caller.</p><p>First, make a folder for the backend:</p><pre>mkdir backend<br>cd backend</pre><p>Then, have Serverless create some boilerplate code for us:</p><pre>serverless create --template aws-python3 --name serverless-chat</pre><p>This command creates a template handler.py and serverless.yml for a service called “serverless-chat”. It also creates a .gitignore in the current directory (which you may delete if you choose).</p><p>Ignoring comments, the initial serverless.yml file will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/036811d2dd484137db9c620a273f39f5/href">https://medium.com/media/036811d2dd484137db9c620a273f39f5/href</a></iframe><p>This file is responsible for configuring how Serverless will deploy your service, including your AWS Lambda functions, and eventually, any resources your service needs.</p><p>The handler.py file will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/154f6655e71e669a97d28b7bfb1d7075/href">https://medium.com/media/154f6655e71e669a97d28b7bfb1d7075/href</a></iframe><p>As you might expect, this file will actually hold the code for the deployed AWS Lambda functions. You can split the methods into separate files if you wish, but the tutorial will keep everything in handler.py for simplicity.</p><p>These template files together make a simple Hello World function that can be immediately deployed. Let’s do it!</p><pre>serverless deploy</pre><p>If all goes well, you will see output that looks like this:</p><pre>Serverless: Packaging service...<br>Serverless: Excluding development dependencies...<br>Serverless: Creating Stack...<br>Serverless: Checking Stack create progress...<br>.....<br>Serverless: Stack create finished...<br>Serverless: Uploading CloudFormation file to S3...<br>Serverless: Uploading artifacts...<br>Serverless: Uploading service serverless-chat.zip file to S3 (307 B)...<br>Serverless: Validating template...<br>Serverless: Updating Stack...<br>Serverless: Checking Stack update progress...<br>................<br>Serverless: Stack update finished...<br>Service Information<br>service: serverless-chat<br>stage: dev<br>region: us-east-1<br>stack: serverless-chat-dev<br>resources: 5<br>api keys:<br>  None<br>endpoints:<br>  None<br>functions:<br>  hello: serverless-chat-dev-hello<br>layers:<br>  None</pre><p>And you can invoke your function with the command:</p><pre>serverless invoke -f hello</pre><p>Which should return something like:</p><pre>{<br>    &quot;statusCode&quot;: 200,<br>    &quot;body&quot;: &quot;{\&quot;message\&quot;: \&quot;Go Serverless v1.0! Your function executed successfully!\&quot;, \&quot;input\&quot;: {}}&quot;<br>}</pre><p>Great, it’s alive! But right now, the only way to invoke the function is via the command line: if we’re going to build an API, it needs to be accessible via a public URL. And didn’t we want a “ping” function? Let’s change that.</p><p>In handler.py, change the “hello” function name to “ping” , and change the body to simply echo back “PONG!”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17b33902b771c6da1a562653235b7cdf/href">https://medium.com/media/17b33902b771c6da1a562653235b7cdf/href</a></iframe><p>In serverless.yml, update the “hello” function to be named “ping” and use your new handler function. Also, add an event to trigger the function when the /ping URL path is requested:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a079522676ce333cb422bd7f5a57e1b6/href">https://medium.com/media/a079522676ce333cb422bd7f5a57e1b6/href</a></iframe><p>Now redeploy:</p><pre>serverless deploy</pre><p>Near the end of the deployment output, you should see a list of public endpoints your service exposes. It will resemble the following:</p><pre>...<br>endpoints:<br>  GET - https://**********.execute-api.us-east-1.amazonaws.com/dev/ping<br>...</pre><p>You can visit this URL with a browser, or test it via curl or any other command line tool you prefer. (Use your own endpoint URL when testing)</p><pre>curl &quot;https://**********.execute-api.us-east-1.amazonaws.com/dev/ping&quot;</pre><pre>PONG!</pre><p>Success!</p><h3>Step 4: Add and View Logs</h3><p>We are eventually going to need to debug our API. Using a serverless infrastructure makes this a little trickier, since there is no server to log into and test on, but it is still doable with <a href="https://aws.amazon.com/cloudwatch/">AWS CloudWatch</a>.</p><p>Any <a href="https://docs.aws.amazon.com/lambda/latest/dg/python-logging.html">print statements or Logger methods</a> inside a Lambda function will generate a log entry in AWS CloudWatch. Using the Logger methods will give us the time stamp and filterable log levels by default, so we will use those in this tutorial.</p><p>Return to handler.py, and add code to import the logging module, create a Logger, and use it in the ping function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc79566282b830cf8c34b00b68bce8f4/href">https://medium.com/media/cc79566282b830cf8c34b00b68bce8f4/href</a></iframe><p>Redeploy the backend, then invoke the ping function however you wish.</p><pre>serverless deploy</pre><pre>...</pre><pre>curl &quot;&lt;YOUR_PING_ENDPOINT&gt;&quot;</pre><p>Now, <a href="https://console.aws.amazon.com/cloudwatch/home">log into CloudWatch</a>, and go to Logs. You should see a new Log Group has been created for AWS Lambda ping function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-T5SKsuklrZG7CcBjfPfMQ.png" /></figure><p>Click on that Log Group, then on the latest Log Stream, and you should see the logs generated during the most recent invocation of the function, including your new “Ping requested” entry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukjRySYZGAldHeuZes-Ztg.png" /></figure><p>This will be one of your best assets when debugging more complicated functions on AWS Lambda / Serverless.</p><h3>Step 5: Add the Database + Python Dependencies</h3><p>We’re just about ready to start writing our WebSocket API, but first, we need a database. We will use <a href="https://aws.amazon.com/dynamodb/">DynamoDB</a> in this tutorial, a NoSQL database that’s easy to setup.</p><p>We need a table for keeping track of our WebSocket Connection IDs, and another for storing the messages sent in the chat rooms. Let’s create the Connections table first.</p><p><a href="https://console.aws.amazon.com/dynamodb/home">Log into DynamoDB</a>, then click “Create table”. Give the table a name, and enter “ConnectionID” as the Partition key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PP5pfVjs6ZSaEmp7iIQN1w.png" /></figure><p>Once the Connections table is finished loading, click “Create table” again. Give it name, and this time, enter “Room” as the Partition key, and “Index” as a Number Sort key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbqVUxSiVvfah6eM_FaB7Q.png" /></figure><p>Create it. Click on the Items tab once it’s finished if you wish to double-check your Primary key columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypebO0UctKof6K68IiK66Q.png" /></figure><p>It’s empty now, but you can return to this tab to see the items in the table as they are entered.</p><p>Now we need to setup our backend code to be able to interact with the database. In Python, you interact with Amazon services through the <a href="http://boto.cloudhackers.com/en/latest/">boto module</a>. Amazon Lambda actually already has boto installed by default on its servers, but at the time of this post, the pre-installed version is out of date, and missing key features we need, so we will need to specify our own anyway.</p><p>First, open serverless.yml, and add an iamRoleStatement for permitting DynamoDB actions (change “us-east-1” if you are in a different region).</p><pre>provider:<br>    name: aws<br>    runtime: python3.7<br>    iamRoleStatements:<br>        - Effect: Allow<br>          Action:<br>              - &quot;dynamodb:PutItem&quot;<br>              - &quot;dynamodb:GetItem&quot;<br>              - &quot;dynamodb:UpdateItem&quot;<br>              - &quot;dynamodb:DeleteItem&quot;<br>              - &quot;dynamodb:BatchGetItem&quot;<br>              - &quot;dynamodb:BatchWriteItem&quot;<br>              - &quot;dynamodb:Scan&quot;<br>              - &quot;dynamodb:Query&quot;<br>          Resource:<br>              - &quot;arn:aws:dynamodb:us-east-1:*:*&quot;</pre><p>To specify our python dependencies, we will use a plugin called “<a href="https://www.npmjs.com/package/serverless-python-requirements">serverless-python-requirements</a>”, which will read a requirements.txt file in the root deployment directory, and install them for us before pushing the handler function to AWS Lambda. Neat!</p><p>First, install the plugin locally by running:</p><pre>serverless plugin install -n serverless-python-requirements</pre><p>Note that this will also create package.json, package-lock.json, and a node_modules folder in the current directory.</p><p>Next, add the following lines to serverless.yml (the first two may have already been added by the above command):</p><pre>plugins:<br>    - serverless-python-requirements</pre><pre>custom:<br>    pythonRequirements:<br>        dockerizePip: true<br>        noDeploy: []</pre><p>The first two lines tell serverless to use the python-requirements plugin, and the remaining lines are how we configure it.</p><p>We need dockerizePip because Amazon Lambda handlers run a specific version of Linux we may not currently be developing on. Thus, all dependencies are installed within a Docker instance before being pushed to AWS. (Note, this requires you to download and install <a href="https://www.docker.com/get-started">Docker</a>, if you haven’t already).</p><p>The noDeploy line tells Amazon Lambda to use our version of any packages we specify if they happen to already be installed. The updated serverless.yml file should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54a4c13d72c474b2495f18102a4d5113/href">https://medium.com/media/54a4c13d72c474b2495f18102a4d5113/href</a></iframe><p>Finally, install the boto3 and botocore python packages:</p><pre>pip install boto3 botocore</pre><p>And create a requirements.txt file listing them as dependencies:</p><pre>pip freeze &gt; requirements.txt</pre><p>At this point, my requirements.txt looks like this (you may have different version numbers):</p><pre>boto3==1.9.130<br>botocore==1.12.130<br>... (Less important packages) ...</pre><p>And my backend directory looks like this:</p><pre>.<br>├── .gitignore<br>├── .serverless/<br>├── handler.py<br>├── node_modules/<br>├── package-lock.json<br>├── package.json<br>├── requirements.txt<br>└── serverless.yml</pre><p>We should now be able to read and update the database in our Python handler. Let’s modify the ping method to prove it.</p><p>Import boto3 and create a Dynamo DB resource at the top of the file, then write some code to access the Messages table and add an item to it. You may find the <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB">boto3 documentation</a> helpful.</p><p>The updated handler.py should somewhat resemble this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21de7d06db6e439a79a9d8a4dc81623d/href">https://medium.com/media/21de7d06db6e439a79a9d8a4dc81623d/href</a></iframe><p>Note that I’ve added some additional keys to the Item placed in the Database:</p><ul><li>Timestamp: keeps track of when the message was created</li><li>Username: username of the person creating the message</li><li>Content: the actual text in the message</li></ul><p>Now redeploy and invoke the ping function:</p><pre>serverless deploy</pre><pre>...</pre><pre>curl &quot;&lt;YOUR_PING_ENDPOINT&gt;&quot;</pre><p>If you visit DynamoDB, then go to the Messages table and click on the Items tab, you should see the newly created message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-f2WpqDS5QK7hT0_7-dJg.png" /></figure><p>If not, visit CloudWatch as described in Step 4 to help you debug what went wrong.</p><h3>Step 6: Write the WebSocket Handlers</h3><p>We’re finally getting to the good stuff! With setup out of the way, it’s time to write the core WebSocket handlers.</p><p>Our API will support four functions: connectionManager for handling connecting and disconnecting from the WebSocket, sendMessage for sending a message to the chat room, getRecentMessages for retrieving the most recent chat messages (used on first connection), and defaultMessage to gracefully handle requests not supported by the API.</p><p>Open handler.py and create a function for the connection manager:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cc20fad002d0c72417add93d2e267ef/href">https://medium.com/media/7cc20fad002d0c72417add93d2e267ef/href</a></iframe><p>Amazon Lambda <a href="https://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html">passes event data</a> through the event argument, which we can use to access the connectionId. We can also access the eventType, which tells us whether the user is connecting or disconnecting from the WebSocket.</p><p>Next, write the code to add the connectionId to the Connections table on connect, and remove it on disconnect.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0796cf264fa7ec70ff76f6991f2f256/href">https://medium.com/media/b0796cf264fa7ec70ff76f6991f2f256/href</a></iframe><p>Finally, the function should return a response dictionary whenever it exits, like our ping function does. We will need to do this a lot, so I created a helper function that does the packaging for me.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cc29d13dc5ca5f6e75e47a8bde44e42/href">https://medium.com/media/9cc29d13dc5ca5f6e75e47a8bde44e42/href</a></iframe><p>Next, let’s create the handler for sending a message. The first thing we need to do is parse the message data from the client. The client needs to provide the content of the message, and for now, it also needs to provide the username of the person sending it as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df0672fd9af0dc426600439f8c8ea2bc/href">https://medium.com/media/df0672fd9af0dc426600439f8c8ea2bc/href</a></iframe><p>Before we update the WebSocket listeners, we should store the new message in the database. A Message item in our project has fields for the Username, Content, Room, Index, andTimestamp. Username and Content are provided to us by the client. For now, everyone will post to the same Room, so we can set that to some constant string (if we wanted to support private chats, the client would send the Room to post to as well). We will manually calculate the Index by querying for the last Message in the database, and incrementing it’s index by one. Finally, we can easily calculate the Timestamp using Python’s time module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86721120f0cca2b4ef17ac9a902ae6b3/href">https://medium.com/media/86721120f0cca2b4ef17ac9a902ae6b3/href</a></iframe><p>Finally, the message should be sent to all listeners connected to the WebSocket. First, we query for all connection IDs in the Connections table, then we send the message (stripped of all unnecessary data) to each of those connections. To actually send the message, we can use the post_to_connection method in <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/apigatewaymanagementapi.html#ApiGatewayManagementApi.Client.post_to_connection">boto3’s API Gateway Management API</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cef7cd9e980939a6b846fdc3d085284f/href">https://medium.com/media/cef7cd9e980939a6b846fdc3d085284f/href</a></iframe><p>Now, let’s write the handler for getting the 10 most recent messages. To do this, we query for the first 10 items in reverse index order, achieved by setting Limit=10 and ScanIndexForward=False. However, this gives us the raw Message items in reverse chronological order, so before sending it to the client, we reverse the list, and strip the items to just include the username and content.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bc79890c02be77e45679e450450a03f/href">https://medium.com/media/5bc79890c02be77e45679e450450a03f/href</a></iframe><p>Lastly, we will write the default message handler, which simply logs the event and returns a 400 status code. I also took the database test out of the ping function handler, and updated it to use the _get_response helper function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b34657cdd9766b569369f66c3bc2750/href">https://medium.com/media/3b34657cdd9766b569369f66c3bc2750/href</a></iframe><p>With all of the handler functions written, we just need to properly configure them for Serverless. Open serverless.yml and add the following lines to provider:</p><pre>provider:<br>    ...<br>    websocketApiName: serverless-chat-api<br>    websocketApiRouteSelectionExpression: $request.body.action</pre><p>The first line is used internally by API Gateway when setting up the WebSocket endpoint. The second specifies which key in the data dictionary is used to determine the “route”, which dictates the API function to be run (more on this shortly).</p><p>We also need to give Serverless permission to manage the WebSocket connections:</p><pre>provider:<br>    ...<br>    iamRoleStatements:<br>        - Effect: Allow<br>          Action:<br>              - &quot;execute-api:ManageConnections&quot;<br>          Resource:<br>              - &quot;arn:aws:execute-api:*:*:**/@connections/*&quot;<br>        ...</pre><p>Finally, we need to link our function handlers to the WebSocket routes, such as below:</p><pre>functions:<br>    ...<br>    defaultMessage:<br>        handler: handler.default_message<br>        events:<br>            - websocket:<br>                route: $default<br>    ...</pre><p>Note that $connect, $disconnect, and $default are special routes, and require the prepended “$” if you want the respective built-in WebSocket events. No other routes need the “$”.</p><p>The final serverless.yml file should resemble this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90b86c90218913eb71f23c09ce36163d/href">https://medium.com/media/90b86c90218913eb71f23c09ce36163d/href</a></iframe><p>The WebSockets API is finally ready. Redeploy:</p><pre>serverless deploy</pre><p>And reexamine the outputted endpoints. You should see a new one has appeared under your ping function:</p><pre>...<br>endpoints:<br>  GET - &lt;YOUR_PING_ENDPOINT&gt;<br>  wss://**********.execute-api.us-east-1.amazonaws.com/dev<br>...</pre><p>The new one is your WebSocket endpoint. You can test it with any tool you wish. A simple option is <a href="https://github.com/websockets/wscat">WebSocket cat</a>, which you can install with the following command:</p><pre>npm install -g wscat</pre><p>Once installed, connect to your WebSocket endpoint:</p><pre>wscat -c &lt;YOUR_WEBSOCKET_ENDPOINT&gt;</pre><p>Then send it requests, using “action” as the route value:</p><pre>{&quot;action&quot;: &quot;sendMessage&quot;, &quot;username&quot;: &quot;test-websocket-user&quot;, &quot;content&quot;: &quot;Testing the Websocket API.&quot;}</pre><p>As before, you can use the CloudWatch and DynamoDB consoles to help you debug if anything went wrong.</p><h3>Step 7: Write a Client</h3><p>With the backend fully functional, we can now write a simple client to interact with it. This tutorial will use <a href="https://www.djangoproject.com/">Django</a>, a popular Python web framework.</p><p>(Note: The focus of this tutorial is on Serverless and WebSockets, not on building a client, therefore I will be assuming some familiarity with Django, and skimming any non-WebSocket related components.)</p><p>First, install Django:</p><pre>pip install Django</pre><p>Then move into the directory containing the backend directory, and start a new Django project.</p><pre>django-admin startproject project<br>mv project client</pre><p>Then create a new “chat” app in the project.</p><pre>cd client<br>python manage.py startapp chat</pre><p>My repository now looks like this:</p><pre>.<br>├── backend/<br>├── client/<br>    ├── chat/<br>        ├── __init__.py<br>        ├── admin.py<br>        ├── app.py<br>        ├── migrations/<br>        ├── models.py<br>        ├── tests.py<br>        └── views.py<br>    ├── manage.py<br>    └── project/<br>        ├── __init__.py<br>        ├── settings.py<br>        ├── urls.py<br>        └── wsgi.py<br>└── venv/</pre><p>From the client directory, make the following edits:</p><p>In project/settings.py, add “chat” to the INSTALLED_APPS setting.</p><pre>INSTALLED_APPS = [<br>    ...<br>    &#39;chat&#39;,<br>]</pre><p>In project/urls.py, include the chat app URLs at the empty path.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/102afcfbeab9e93c51213cbef592a72e/href">https://medium.com/media/102afcfbeab9e93c51213cbef592a72e/href</a></iframe><p>Move into the chat app directory.</p><pre>cd chat</pre><p>Create a templates directory, and a chat directory inside that one.</p><pre>mkdir templates<br>mkdir templates/chat</pre><p>Inside the new templates/chat directory, create an index.html file for the app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/620fc87311c330092bb3dd9ae28bd47b/href">https://medium.com/media/620fc87311c330092bb3dd9ae28bd47b/href</a></iframe><p>From the chat app directory, create a static directory, and a chat directory inside that one.</p><pre>mkdir static<br>mkdir static/chat</pre><p>Inside the new static/chat directory, create a style.css file to style the index page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e8cdc8639b1a3be13cccf0b286e6efd/href">https://medium.com/media/7e8cdc8639b1a3be13cccf0b286e6efd/href</a></iframe><p>Now we just need to create and route a view to display the new template. Back in the chat app directory, add the following to views.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad2bdf54b6d5e4b07a3f7ba4681a90f0/href">https://medium.com/media/ad2bdf54b6d5e4b07a3f7ba4681a90f0/href</a></iframe><p>Finally, create a file called urls.py and route the index view to the empty path.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01bb1702624dce79e3e69435e8573cbb/href">https://medium.com/media/01bb1702624dce79e3e69435e8573cbb/href</a></iframe><p>Move back into the client directory, apply any initial migrations, and start the Django server.</p><pre>cd ..<br>python manage.py migrate<br>python manage.py runserver</pre><p>Visit localhost:8000 in a browser, and you should see the index page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JNIs7SCMJV83Vm7KZgTPgg.png" /></figure><p>Of course, it doesn’t actually connect to anything, and the Post button at the bottom does nothing at the moment. Time to fix that.</p><p>From the chat app directory, create a new file called custom.js in the static/chat directory. This file will contain our WebSocket interaction code for the client.</p><p>Start by creating a function to setup the WebSocket, and initialize a socket variable. Javascript has a <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket">built-in WebSocket api</a>, but I like to use this <a href="https://github.com/joewalnes/reconnecting-websocket">reconnecting WebSocket library</a> for pages that never want to close a WebSocket connection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e95669e9670c63e8d0fe6212d252e92/href">https://medium.com/media/4e95669e9670c63e8d0fe6212d252e92/href</a></iframe><p>Now, we define callback functions that invoked on certain WebSocket events. For example, when the WebSocket is initially opened, the function at socket.onopen will be invoked.</p><p>For our onopen callback function, we want to call the getRecentMessages API function, to initially populate the message list. The route key for our API is “action”, so we create a dictionary setting “action” to “getRecentMessages”, serialize it with JSON, then send it on the socket.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/002e8031294c97252ae4ed8cbe9a42cb/href">https://medium.com/media/002e8031294c97252ae4ed8cbe9a42cb/href</a></iframe><p>The socket.onmessage callback is invoked whenever the client receives data on the WebSocket. For our app, we just want to deserialize the data, then display the new message(s) in the message list.</p><p>Some extra logic is included to display “You” instead of the username for messages posted by the current user. Since users don’t have usernames yet (as there is nothing to log into), we use a randomly generated number to make a fake username.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c32b0d8659afdc50e27196501ec555cb/href">https://medium.com/media/c32b0d8659afdc50e27196501ec555cb/href</a></iframe><p>Finally, write a method to post a new message. We just need to get the text in the input field, then send it on the socket with “sendMessage” as the “action”, our generated username as the “username”, and the text as the “content”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5b1d683d075463c3c48ddb8d780dc07/href">https://medium.com/media/d5b1d683d075463c3c48ddb8d780dc07/href</a></iframe><p>Finally, return to index.html in the templates/chat directory. Link the new custom.js script, setup the WebSocket connection on page load, and post a new message when the Post button or &lt;Enter&gt; is pressed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa26b8cb8f501492563124f3e021bc67/href">https://medium.com/media/fa26b8cb8f501492563124f3e021bc67/href</a></iframe><p>Now, go back to the client directory, and restart the server.</p><pre>cd ..<br>python manage.py runserver</pre><p>Reload localhost:8000 in your browser window. You should see up to the first 10 messages in the databases initially loaded, and you should be able to post messages now as well.</p><p>For even more fun, try opening multiple browser windows to localhost:8000 at once. All clients should update when a new message is posted, and they should be able to communicate with each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uqTMClSeLvD_ZzPzxgrgxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2rPnSZCGuAaxCbps8i4uyA.png" /></figure><h3>Step 8: Secure the App</h3><p>The bulk of the functionality has been written at this point, but there is no persistent sense of identity, and malicious users could pretend to be anyone else anyway by just changing the Javascript. A real application would almost certainly require an identity verification mechanism, and could not rely on client-side code (such as Javascript) to provide that information to the backend, as it cannot be trusted.</p><p>Therefore, to make the app more realistic, we will add Login and Sign Up views (leveraging the ones built into <a href="https://github.com/lgoodridge/django-uniauth">django-uniauth</a>), and protect calls to the backend API with JWT. Token-based authentication is currently the most popular way to secure WebSocket APIs, and JWT is itself a popular and simple Token-based authentication scheme, making it a suitable choice.</p><p>First, install django-uniauth.</p><pre>pip install django-uniauth</pre><p>Then, in project/settings.py add “uniauth” toINSTALLED_APPS.</p><pre>INSTALLED_APPS = [<br>    ...<br>    &#39;uniauth&#39;,<br>]</pre><p>Set AUTHENTICATION_BACKENDS to an appropriate backend. (You may have to create the setting, if it is not already present).</p><pre>AUTHENTICATION_BACKENDS = [<br>    &#39;uniauth.backends.UsernameOrLinkedEmailBackend&#39;,<br>]</pre><p>And add the following settings:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e0e913ca3e8d586e46e4225c5598d00/href">https://medium.com/media/7e0e913ca3e8d586e46e4225c5598d00/href</a></iframe><p>The first line sets which URL a user is redirected to when they try to access a view protected by the login_required decorator without being logged in. The second line sets which URL they are redirected upon manually logging in. The third removes the CAS login option from the Login page, since we don’t have any CAS servers to log into.</p><p>The fourth line tells Django to print all outgoing emails to the console. django-uniauth uses emails for things like email verification, so this is an easy way to still get that functionality locally without setting up an actual SMTP backend. The last line sets the “from” address in those emails to an appropriate name.</p><p>Next, include the package’s URLs in project/urls.py.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f8eee493fc40ee7d72b63dc636f4d5f/href">https://medium.com/media/4f8eee493fc40ee7d72b63dc636f4d5f/href</a></iframe><p>Protect the index view in chat/views.py with the provided login_required decorator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72e91139bfd48eba321c9c3be7cdf5ae/href">https://medium.com/media/72e91139bfd48eba321c9c3be7cdf5ae/href</a></iframe><p>Lastly, move back to the client directory, apply any new migrations, and restart the server.</p><pre>python manage.py migrate<br>python manage.py runserver</pre><p>Upon visiting localhost:8000 in your browser, you should now see the django-uniauth Login page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GD30ewbiWlLcuNVSP6AlMg.png" /></figure><p>Create an account either by clicking “Create an Account” and going through the Sign-up process (check the console window running the server to get the email verification link!), or via Django’s createsuperuser command.</p><pre>python manage.py createsuperuser</pre><p>Either way, once an account has been created, sign in and you should be brought back to the index page.</p><p>Now that we have proper user authentication, let’s set up JWT. We will use the <a href="https://pyjwt.readthedocs.io/en/latest/">PyJWT library</a> in this tutorial. First, install it.</p><pre>pip install pyjwt</pre><p>Then move into your backend directory, and add it to your requirements.txt. The added line should resemble this:</p><pre>PyJWT==*.*.*</pre><p>You will see the version number at the end of the output from the pip install command. Alternatively, you could run pip freeze to view all installed packages, then copy the line beginning with “PyJWT” into requirements.txt.</p><p>Next, open handler.py, and modify the connect handler to read a token passed as a URL parameter, and attempt to decode it using a string of your choice (in this case, I’m using “FAKE_SECRET”). This string will be the shared secret between the backend API and client app that JWT uses to encode / decode the tokens. Thus, if the JWT can successfully decode the token (it will verify the signature automatically as part of the decode method), we know it was created by our client application.</p><p>If no token was provided, or the token fails to decode, the connection should fail immediately.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0cd1e23ed7ddb134802c158edd082b4/href">https://medium.com/media/f0cd1e23ed7ddb134802c158edd082b4/href</a></iframe><p>We will also use JWT in the send_message function to ensure users can’t spoof their usernames. Edit send_message to require token as a data field instead of username, then verify the token, and extract the username from the payload instead if successful (we will set up the client to comply with this shortly). Terminate the function early if the token fails to verify.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/213d025df3e3417b6fa21755b7c2e204/href">https://medium.com/media/213d025df3e3417b6fa21755b7c2e204/href</a></iframe><p>Then, redeploy the backend API.</p><pre>serverless deploy</pre><p>Back in the client directory, move to your chat app directory and open views.py. Modify the index view to encode a token with the username contained in the payload, and your chosen secret string as the secret, and pass the token as part of the view context.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b148251cdec9d2fa39bd5b7c1ca2e163/href">https://medium.com/media/b148251cdec9d2fa39bd5b7c1ca2e163/href</a></iframe><p>Next, open static/chat/custom.js and remove the randomly generated username. Modify setupWebSocket to accept a username and token as arguments, and pass the token as a URL parameter when connecting to the WebSocket. Modify postMessage to accept a token parameter, and include it as part of the message dictionary instead of username.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fccac1dcb4d4c1945a64dfaa7397e6a/href">https://medium.com/media/7fccac1dcb4d4c1945a64dfaa7397e6a/href</a></iframe><p>Then open templates/chat/index.html and modify the event handlers to pass the appropriate arguments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31f6d387f2d9e285e844bf14b8025505/href">https://medium.com/media/31f6d387f2d9e285e844bf14b8025505/href</a></iframe><p>Now restart the client server and check out the final product!</p><pre>python manage.py runserver</pre><p>It should be functionally equivalent to the last time the app was run, but now the username of sent messages will match that of the logged in user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5LhdD7NRMWA1lmojHt6JAw.png" /></figure><h3>And that’s it!</h3><p>You have now built a serverless WebSocket application from scratch, and have hopefully learned a couple of things along the way.</p><p>You can find the code used in this tutorial at <a href="https://github.com/lgoodridge/serverless-chat">this Github repo</a>. And feel free to leave any feedback in the comments!</p><p><a href="https://gitconnected.com/learn/python">Learn Python - Best Python Tutorials (2019) | gitconnected</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54cbc432e4f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/creating-a-chat-app-with-serverless-websockets-and-python-a-tutorial-54cbc432e4f">Creating a Chat App with Serverless, Websockets, and Python: A Tutorial</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding CAS authentication to your Django app with django-uniauth]]></title>
            <link>https://medium.com/@ldgoodridge95/adding-cas-authentication-to-your-django-app-with-django-uniauth-13ff4e1e7bfa?source=rss-c3e8f08beacc------2</link>
            <guid isPermaLink="false">https://medium.com/p/13ff4e1e7bfa</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Lance Goodridge]]></dc:creator>
            <pubDate>Sun, 31 Mar 2019 01:08:55 GMT</pubDate>
            <atom:updated>2019-06-06T20:02:40.422Z</atom:updated>
            <content:encoded><![CDATA[<p>Adding CAS support to your webapp doesn’t need to be difficult. Existing packages such as <a href="https://github.com/python-cas/python-cas">python-cas</a> and <a href="https://github.com/mingchen/django-cas-ng">django-cas-ng</a> have been the go-to tools for enabling CAS on Django apps for some time, but either require complex setup (in the case of python-cas), or restrict your app to a single login server with no built-in support for alternate authentication mechanisms (django-cas-ng).</p><p><a href="https://github.com/lgoodridge/django-uniauth">django-uniauth</a> trivializes the setup process while supporting multiple CAS servers and integration with custom authentication schemes should your app need to grow beyond university campuses. This tutorial shows how to use <strong>django-uniauth</strong> to setup CAS authentication for your app in 5 simple steps.</p><h3>(Optional) Setup: Make a Django app</h3><p>We need an app to add CAS authentication to it! You may skip this step if you already have a Django app built.</p><p>For this tutorial, we will be using a <a href="https://github.com/lgoodridge/example-django-app">pre-made example app</a> that uses the built-in Django login / logout views and displays a simple index page.</p><p>To start, download the source code:</p><pre>git clone https://www.github.com/lgoodridge/example-django-app.git</pre><p>Then, install Django (as always, it’s recommended to <a href="https://docs.python.org/3/library/venv.html">use a virtual environment</a> when installing requirements for a Python project):</p><pre>pip install django</pre><p>Next, migrate the database:</p><pre>cd Example-Django-App/example_app<br>python manage.py migrate</pre><p>Finally run it:</p><pre>python manage.py runserver</pre><p>If everything went well, visiting <strong>localhost:8000</strong> in your web browser should display a very simple index page that prompts you to Login (although there aren’t any users to log into).</p><p>Congratulations! We now have a simple Django app that we can add CAS authentication to.</p><h3>Step 1: Install django-uniauth</h3><p>Run the following command:</p><pre>pip install django-uniauth</pre><h3>Step 2: Update settings</h3><p>Open your <strong>settings.py</strong> file, and add ‘uniauth’ to the <strong>INSTALLED_APPS</strong> setting:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39f5c0702198c7f632a9b960993d3c5c/href">https://medium.com/media/39f5c0702198c7f632a9b960993d3c5c/href</a></iframe><p>Add the Uniauth CAS backend to your authentication backends. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/317072a9da3adc8b1bf3ad67d53c2389/href">https://medium.com/media/317072a9da3adc8b1bf3ad67d53c2389/href</a></iframe><p>Lastly, add the following Uniauth settings:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08b04dc6c2d51ba11c5fbe21a13505a8/href">https://medium.com/media/08b04dc6c2d51ba11c5fbe21a13505a8/href</a></iframe><p>The first line sets the URL for the login view. The next one indicates that we don’t want to display Uniauth’s standard login form (which contains Username / Password fields, a Sign Up link, and so on) — we only want CAS authentication for this tutorial. The last line ensures that when we logout using Uniauth, we log out on the CAS server as well.</p><h3>Step 3: Add the URLs</h3><p>Open your <strong>urls.py</strong> and include the Uniauth CAS URLs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffb9554d9b9871b0b50e1ac4563a34d8/href">https://medium.com/media/ffb9554d9b9871b0b50e1ac4563a34d8/href</a></iframe><p>(If you are using the provided example app, replace the existing <strong>url(https://medium.com/%E2%80%98accounts/%E2%80%99,%C2%A0%E2%80%A6)</strong> line with the above url line in <strong>example_app/urls.py</strong>)</p><h3>Step 4: Prepare database + static files</h3><p>Apply the Uniauth migrations:</p><pre>python manage.py migrate</pre><p>If you are using a custom mechanism for serving static files (as you should be on any real application), you will also need to recollect those:</p><pre>python manage.py collectstatic</pre><h3>Step 5: Add the CAS server(s)</h3><p>Now, add the CAS server(s) you wish to support:</p><pre>python manage.py add_institution &lt;server_name&gt; &lt;server_url&gt;</pre><p>The <strong>server_name</strong> should be a name of your choice for the server, and <strong>server_url</strong> should point to the root URL of a CAS protocol compliant service.</p><p>For example, to support CAS login at Princeton University, you could run:</p><pre>python manage.py add_institution Princeton <a href="https://fed.princeton.edu/cas/">https://fed.princeton.edu/cas</a>/</pre><h3>Finally: Run it!</h3><p>Relaunch the django server:</p><pre>python manage.py runserver</pre><p>Then visit <strong>localhost:8000</strong> to see it in action. If you go to <strong>localhost:8000/accounts/login</strong> (or click the ‘Login’ link on the index page of the example app), you should now see the login page for your chosen CAS server, or prompted to select one to log into first, if you’ve added more than one.</p><p>Successfully authenticating will display the index page showing that you are now logged in with username <strong>cas-&lt;server_name&gt;-&lt;cas_id&gt;</strong>.</p><h3>Bonus: Enforcing Authentication</h3><p>You often want to enforce that a user is authenticated before they may access a certain view. Uniauth offers a <strong>login_required</strong> function decorator (which works exactly like Django’s <a href="https://docs.djangoproject.com/en/2.1/topics/auth/default/#django.contrib.auth.decorators.login_required">built-in version</a>) for that very purpose.</p><p>For example, if you are using the example app, you could protect the index page by opening <strong>core/views.py</strong> and inserting the additions on lines 2 and 4:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/252d008d3c83092c3e924d2b02ad66d1/href">https://medium.com/media/252d008d3c83092c3e924d2b02ad66d1/href</a></iframe><p>Now when you visit the index page, you should be redirected to the login page first if you aren’t already authenticated.</p><p>And that’s it! Your app is now protected by CAS, and you can move on to more difficult and interesting endeavors (such as <a href="https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/">deployment</a>).</p><p>Please look at, and star <a href="https://github.com/lgoodridge/django-uniauth">the repo</a> if this tutorial was helpful, and any comments or feedback is appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13ff4e1e7bfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>