Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Getting started with Sanic: the asynchronous, uvloop based web framework for Pyt ...

$
0
0

uvloop has been making waves in the python world lately as a blazingly fastdrop-in for asyncio’s default event loop. Sanic is a Flask-like, uvloop-based web framework that’s written to go fast . It is also named after the popular Sanic Internet meme, a poorly drawn version of Sonic the Hedgehog .

Sanic is made for Python 3.5 . The framework allows you to take advantage of async/await syntax for defining asynchronous functions. With this, you can write async applications in Python similar to how you would write them in Node.js.

Responding to basic HTTP requests

The “Hello World” example with Sanic looks like this:

fromsanicimportSanic fromsanic.responseimporttext app = Sanic() @app.route("/") asyncdefhello(request): return text("Hello World!") if __name__ == "__main__": app.run(host="0.0.0.0", port=8000)

Create a new directory for this project, and paste that code into a new file called app.py . In order to run this code, you’ll also want to create a virtual environment (make sure to use Python 3 when creating the environment) and run the following command to install Sanic:

pipinstallsanic

And run the application:

pythonapp.py

And visit http://localhost:8000 to see “Hello World!” on the page.

“Hello World” is nice, but let’s see what else we can do. In this next example, we’ll switch things up a bit to figure out how to work with query arguments in the request data. Change the code in app.py to the following:

from sanicimport Sanic from sanic.responseimport text app = Sanic() @app.route("/") asyncdef hello(request): # request.args is a dict where each value is an array. return text("Hello {}".format(request.args["name"][0])) if __name__ == "__main__": app.run(host="0.0.0.0", port=8000)

Run the code again and this time visit http://localhost:8000/?name=Sam . Feel free to replace “Sam” with your own name. When you visit the web page, it should be greeting you by name.

Responding to text messages

Next we canuse Sanic to do something useful. We’ll write code that usesTwilio to respond to a text message. You’ll need a Twilio account for this, but don’t worry you can sign up for free .

When someone texts your Twilio number, Twilio makes an HTTP request to your app. Details about that SMS are passed via the request parameters. Twilio expects an HTTP response from your web app in the form of TwiML , which is a set of simple XML tags used to tell Twilio what to do next.

Replace the code in app.py again with the following code to quickly respond to a text message:

from sanicimport Sanic from sanic.responseimport text app = Sanic() @app.route("/sms") asyncdef hello(request): # request.form is a dict where each value is an array. message_body = request.form["Body"][0] # Since we are just responding with a message, we can return a String return text("You said: {}".format(message_body)) if __name__ == "__main__": app.run(host="0.0.0.0", port=8000)

All you need to do is grab a Twilio number or use a phone number that comes with your trial account and configure it to send POST requests to your app whenever you receive a text message.

Our app needs a publicly accessible URL. To avoid having to deploy every time we make a change, we’ll use a nifty tool called ngrok to open a tunnel to our local machine.

Ngrok generates a custom forwarding URL that we will use to tell Twilio where to find our application. Download ngrok and run it in your terminal on port 8000

./ngrokhttp 8000

Next we need to point a phone number at our app. Open the phone number configuration screen in your Twilio console . Scroll down to the “a message comes in” field. Before entering your URL you should see:


Getting started with Sanic: the asynchronous, uvloop based web framework for Pyt ...

Punch in the URL for ourmessage route that was generated by ngrok. It should look like http://your-ngrok-url.ngrok.io/sms .

Click save, make sure your application is running andtext your number to get a response.

Rollin’around at the speed of sound

That should be all you need to get started building apps with Sanic. You are officially part of the revolution of meme-driven development .

Of course, Sanic is a brand new framework so expect improvements and changes in the near future. You can even contribute to its open source repository and help build it yourself.

Feel free to drop me a line if you have any question or just want to show off what you built:

Email: sagnew@twilio.com Twitter: @Sagnewshreds Github: Sagnew Twitch (streaming live code): Sagnewshreds

Viewing all articles
Browse latest Browse all 9596

Trending Articles