Async Web Apps with Sanic

Video thumbnail (Frame 0) Video thumbnail (Frame 9134) Video thumbnail (Frame 9869) Video thumbnail (Frame 12949) Video thumbnail (Frame 13814) Video thumbnail (Frame 14965) Video thumbnail (Frame 15784) Video thumbnail (Frame 16464) Video thumbnail (Frame 18730) Video thumbnail (Frame 23476) Video thumbnail (Frame 28810) Video thumbnail (Frame 31482) Video thumbnail (Frame 45154) Video thumbnail (Frame 46174)
Video in TIB AV-Portal: Async Web Apps with Sanic

Formal Metadata

Async Web Apps with Sanic
Title of Series
CC Attribution - NonCommercial - ShareAlike 3.0 Unported:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this license.
Release Date

Content Metadata

Subject Area
Async Web Apps with Sanic [EuroPython 2017 - Talk - 2017-07-10 - Anfiteatro 1] [Rimini, Italy] This talk will introduce you to Sanic, the Python 3 web framework that supports async request handlers with a simple, Flask-like, API. We will start with a Sanic overview and compare it with other similar options before looking at the API and working through a basic app. Our goal here will be to get a feel for the Sanic API and demonstrate how it fits together. After this we will cover some of the more unique and interesting possibilities with Sanic, such as support for websockets and HTTP2. A web framework is often only as powerful as its ecosystem, so we will take a look at some of the popular Sanic extensions for databases, templating and testing.
Point (geometry) Intel Building Group action Multiplication sign Code division multiple access Coroutine Similarity (geometry) Open set Event horizon Number Power (physics) Web 2.0 Latent heat Term (mathematics) Software Energy level Software framework Lie group Social class Task (computing) Mobile app Addition Building Software developer Projective plane Plastikkarte Planning Supersonic speed Database Bit Software maintenance Proof theory Process (computing) Self-organization Speech synthesis Video game Quicksort Clique problem Resultant
Point (geometry) Implementation Statistics Dependent and independent variables Code Moment (mathematics) Stress (mechanics) Supersonic speed Drop (liquid) Inverse element Cartesian coordinate system Mereology Number Web 2.0 Sign (mathematics) Arithmetic mean Internetworking Computer configuration Term (mathematics) Network topology Core dump Software framework Error message Window
Building Dependent and independent variables Different (Kate Ryan album) Software developer Routing
Point (geometry) Revision control Functional (mathematics) Logic Weight Self-organization Protein
Mobile app Goodness of fit Dependent and independent variables Multiplication sign Angle Writing Asynchronous Transfer Mode Template (C++)
Web page Noise (electronics) Server (computing) Functional (mathematics) Structural load Software developer Weight Real-time operating system Entire function Connected space Web 2.0 Software Computer configuration Telecommunication Network socket Software framework Sinc function Library (computing)
Point (geometry) Slide rule Server (computing) Dialect Functional (mathematics) Greatest element Demo (music) Code Augmented reality Weight Multiplication sign Moment (mathematics) Electronic mailing list Gene cluster Bit Event horizon Demoscene Subset Number Connected space Uniform resource locator Pattern language Family Error message
Web page Point (geometry) Email Socket-Schnittstelle Server (computing) Functional (mathematics) Length Multiplication sign Set (mathematics) Client (computing) Mass Mereology Data dictionary Event horizon 2 (number) Number Schwerpunktsystem Codierung <Programmierung> Office suite Exception handling Dialect Information Closed set Core dump Bit Line (geometry) Variable (mathematics) Complete metric space Connected space Network topology Triangle Website Asynchronous Transfer Mode Library (computing)
Slide rule Complex (psychology) Decision tree learning Link (knot theory) Code Interior (topology) 1 (number) Database Line (geometry) Content (media) Connected space Time domain Revision control Repository (publishing) Right angle Communications protocol Message passing Surjective function
Complex (psychology) INTEGRAL Code State of matter Direction (geometry) Multiplication sign Workstation <Musikinstrument> Mereology Food energy Public key certificate Web 2.0 Bit rate Computer configuration Core dump Software framework Extension (kinesiology) Information security Error message Social class Oracle Physical system Texture mapping Software developer Bit Instance (computer science) Statistics Connected space Type theory Arithmetic mean Process (computing) Computer configuration Uniformer Raum Website Software testing Quicksort Physical system Spacetime Point (geometry) Slide rule Mobile app Server (computing) Functional (mathematics) Service (economics) Divisor Connectivity (graph theory) Virtual machine Event horizon Rule of inference Power (physics) Revision control Causality Authorization Software testing Condition number Form (programming) Computer architecture Authentication Standard deviation Multiplication Information Interface (computing) Gender Weight Projective plane Line (geometry) Limit (category theory) Subgroup Particle system Word Loop (music) Network topology HTTP cookie Spectrum (functional analysis) Library (computing)
Pairwise comparison Multiplication sign Projective plane Moment (mathematics) Planning Login Perspective (visual) Particle system Integrated development environment Different (Kate Ryan album) Computer configuration Software framework Library (computing) Physical system
by an offensive wrongful come along today and the 1st thing I want to sort of talk
about quickly is this of there I made in the title
of my talk and specifically is to do with the way it acts and I mean what what is the weather and so he just ignore that and just think of it as Moss building web things with something and which analysts and much more helpful that and you may understand more as I coincidental but I think it was in the best title so what I really want to do today is talk to about my journey learning something can learning the AC bio ecosystem and in terms of doing so what development and so what frameworks the 1st of all just quickly here I'm I'm I'm a Scottish by the stuff I'm speaking of which is extremely hot here and my hotel a seasonal working so if I fall asleep is the latest thing well as an otherwise be having lost the organizers and of maintainer of a number of projects that probably most popular is anchored not so by achieving fairly inactive and I will I'm adipocyte developer habitat as my my job and and in the past and it's of 10 years almost done a lot of Django and floss development have done follow what development so this is really quite interesting and lessons for me in terms of learning about facing quick framework because while the actual development can be very similar this point was of this this class specific mind you need to take some because of otherwise plentiful the UN but 1st of all is sort of a bit about how we how we got to this to check of this and so how do you get to this point of where people are able to use its entire for the for the this kind development and I think all it comes from the transition coming from Python 2 to 3 as you like as a community we are kind of at the tipping point where most people should either be unpleasant feeling now or they should have a clear transition to Python 3 that's on the way and if not going to be enough of of enough to place and not a lot I think that if can make the assumption that most people are on Python 3 than most moral so long life and 3 . 3 or above which means they have the ability to use a single so this talk is not really about what we think Iowa's by just want to quickly so defined for people of a can which is a fairly tricky thing to do because this is something which could have multiple told itself it's a quite a big subject essentially this entire provides people way to have a single-threaded concurrent card using coroutines and essentially you know you have an event with so this is something which is in the tickling you it's not an innovation this encodes twist is been there for a long time terminated on a more recently no yes we made a very popular in the JavaScript world however the cliques of the real important thing about its encloses given everyone a common base to walk on you don't end up silos where all these of twisted projects everyone's can hopefully everyone will stop moving towards the same the standard event with which they can then build an ecosystem around and prove things and something that's a really important thing that's most important the reason co has actually done I have a confession to make that initially when I try to see so now was about 2 to 3 years ago I essentially dismissed that I didn't like it felt awkward and for those that remember in and I guess of the full Python 3 . 5 you had to use a decorator to specify karate and you have to use you from and I just felt kind of awkward to can feel like regular Python but with the addition of await keywords that selects a lot more natural and more comfortable to use up some examples of these have you not too familiar with them you'll see them in the and that is the point of that is I've had a lot better experience using is isn't this time around so if you have looked at and possibly be dismissed if a similar reasons it might be my return to start taking a 2nd look and advantageous to something which is the result the thing which finds assault altogether Sonic is a small contains bare-bones with framework discussed similar spoke to flask and I don't know they have any plans to the time I suspect probably not it's going to so lost is really powerful for being minimal but it's really powerful because of ecosystems built around it and I think that something from the time of and it's because it's which roughly builds the cell and that some of the similar levels of power the the and then once of wondering what was special about something and using a anchor why is it worth the effort compared to Fhloston walking to the founder of the lies so what I said this was not explained and and this is because I'm probably not is encouraged of essentially the develop allows you to sustain or keep multiple connections open at the same time so that means you can take multiple requests processes and then you just be waiting for a prior so say for example you have and aware that which has an endpoint which request something from a database when you curvatures appointments requested the dates basically released by so in the background essentially and then another request to the process of time you keep like switching between the different and events on the outside of the different tasks of the event with so say for example and the the equivalent say something like last would the the every request be processed 1 by 1 the wait for press to start to finish and then you'd be completely sequential whereas with asynchronous of conqueror and the people they don't understand the
reference and the what framework is named after this internet meme in which is how it may be a sign of how serious is that fits in quite well with the Python ecosystem and and the I don't fully understand the mean not to say there is essentially I think he was of a kid or somebody had done a really bad drawing of Sonic the Hedgehog and people just on the hilarious and show that any of these things explored but I mentioned that there is a
kind of an explosion around this entire recently in terms of frameworks and options so warmly may take something over the others and there are a whole bunch of other stuff competing web frameworks which are hoping to that users and the number of reasons and honestly the fairly simple adjusting by the easiest to use which is to get started with an on lost the forwards and very familiar and and it just didn't really do my way it's like it's essentially provides you with a way of doing a request your responses and then you can call out other parts of as need which is exactly how it feels when you watch this lost as well as and that no I so I started using initially probably in early January I think I think it was quite what he is all to be honest and it seems like the most active and see nice is to use but then looking back at the stats now it's really the only 1 steam traction and so only 1 is from the active and you have lots of issues and core question like community discussion so I I think I jumped on the correct tree which was definitely partially lot but also probably a testament to how easy it was to use and it is not it is as easy as you'd expect and there is 1 catch and I found out that something doesn't actually work on windows of moment and the reason for this is that rather than using the native basin Cairo actually uses you need this is a faster implementation of the Sinclair written siphon and largely on its own axis and Linux that's just an implementation detail you can ignore that compatible and drop in replacement baby trying still something Windows you actually get error moment of my full it would fall by tracing code but I found the earliest and the windows they'll actually just to the installation will fail and complained that you really have not multiple windows and so I am not sure those regressional or what happened but availability of windows at some point so this is the inverse of the
mandatory Hello world and which shows you the the so the very bare bones in the and again the reference was quite a lot they will seem very familiar to foster developers unfortunately with the out of this room is quite hard for me to point out there and even with my laser pointer is above me but you can see the so something has the concept of that and and that only 1 acts in the name of my total and present so you define a apt to
represent the what you're building and then you add routes to adjust lighting and foster the key difference here is the basic keyword so if you're not familiar with its entire this is a
syntax was added in Python 3 . 5 or I think all I did not write on the version and what that does is it tells points and then this is a protein this function so that means he a weight on it and it can wait another proteins entirely inside the and otherwise this is just a very simple example is returns the plaintext hello world and and it's a fully working examples as logical siphons told you can get from that and we need to this is the
and so this is the obviously the ASCII and version of the of the drawing of the and this is 1 of the things of insanity is doing really well the we could do some organization and as are and entertainment when you're running your
apps and joking aside is actually reasonably useful because that will only appear when you're writing that in debug mode
so it's a good coverage flight you forgot to turn the debug of otherwise the axon of
the from the standard things you'd expect that
this is just a quick example showing you how you'd return text plain text what is in the 1st example returning Jason and running time engaged in which could obviously the laughter rendered ginger template or something like that but why don't we want to do is this talking through the documentation talking through the the API so you're trying to do something more interesting example and I have left talk you through
the so I think would talk is a 1 of the best ways to demonstrate why they cinco framework can be useful and for those of you who don't know what are away for your JavaScript to speak to your server and essentially real-time communication so rather than polling for updates for example will open a connection 1 page loads and then not just sit there waiting till eventually they can send data to the server as well but will also receive data from the server is a two-way communication and and that's essentially instantaneous mean other than that network latency and that allows you to do real real time so websites um which is good for things like chat or notifications so and I am not fall the WebSocket supported something you need this uh extra package so this is an optional dependency essentially and it's in this entire WebSocket library which is really nice so even if you want to do something with a sinc ROI WebSockets but not with something that's only I think this is the best option is written by I think is 1 of the Charter for developers originally but but noise in China itself was more so when you have and so that you can then use the actor WebSocket and functional decorator search to define a web socket endpoint and so again this is a very simple example so we have
the they say the were tells purity and then we have the of 2 weights
and are tied to the point fabric that's honest enough to explain how have and yes if June knew that stuff it's that this is like clustering strange pattern because it looks to you like this function could just be locked up indefinitely because of wall it's infinitely but actually every time you get to the awaits so when you have the weight what's don't send and their weight WebSocket overseas they will achieve the I O 4 that will happen in the background of be waiting for something to be said or something to be received and then return to the family and other requests can be processed concurrently so that this is why it's so important to have something like this Cairo for this we cannot confirm request you kindly really do WebSockets in something like flossed because it requires you maintain the required that you were maintain the connection and keeping off many connections open it clusters doesn't really work and and the same applies to subjective things there are ways to do in general now and so what do we used to do is run something like tornado twisted and that have a WebSocket server and then that of the general fast server and then that they speak to each other behind the scenes in the subset of locations where you have to do with keeping them all and thinking about and I know this is a very simple example from the augmentation I think we can do something better so in danger of and the endemic gods of medical destroying go to this web address of the kind of interesting to see if this works so as an he born data so you can use your regular cellular data and that faithfully if you're European you won't have any roaming charges now and essentially what this does is it shows the number of people that are connected to and it shows a list of the user regions of people connected and try to load and also the mole might take a moment for the paragraph to start is anyone managed to load how many people are connected doesn't tell you so the had as an error I was worried that might happen but it has had a it's a bit a sudden essentially Superfund showing you I can still working through the code in the same way in 20 plus pretty good so I I don't demo this Tolkien in Gloucester and I had follows the poetic and and I have no idea how many can handle before it falls over so that it seems to be better than Wi-Fi because of how many 31 this body yes of all of you are but this illegal you request the currently open and all being handled and city in the background waiting for the I O events to finish and and the nice thing about it is how little code such a required to make this and so this is a slide where I really needed
to build 2 point biologist from top to bottom
so the 1st 2 variables with topic connected equal set and the user regions essentially
tracking the WebSockets are connected just this number WebSockets is a connected with so that these regions is then just a dictionary regions which I routinely sent to the browser and and we have a proteome again which is called feet and when the requested opened the Woodstock is added to the connected sets and then we just take the user region from the request and add that to the user agents dictionary and I have a little consisting of which is useful from the Council I promise a remove that fall in office of the last time I give this talk and over the past and then we're going to be the actually um which is something here which is then in the sending the data back to the client so we can see is I WebSocket of Sandinista sending trees in this and in these regions which is a bit of a set and then the WebSockets binds the length of that's reducing the numbers more efficient the and then we wait to that it to be said and it just happened over and what we have the next line is the is encoded sleep so it's sleeping 0 . 1 2nd so that means it's sending the information updates to the client and every 0 . 1 seconds assuming everything goes at the 1 thing that's really important here is an example of what we need to understand this in Cairo and make sure you don't do anything which is blocking you can't use or you could maybe about it you shouldn't use the triangle sleep function that you have to use a single mostly because we see when using the kind of sleep they which just block that we're at that point when you use a single mostly there then releases back to the event and allows other requests to be processed so the thing was something like this and so it's not the accounting what encouraged to see to make sure you put this in a way that is blocking and this is 1 of the colleges I find is that you might want be to try to use a third-party library that light doesn't blocking then that will affect your your off and then in the finally part of the Detroit finally we just isn't enough so we remove the connectives WebSocket and then we remove the user region and and print out as the number of connector sockets for multivariate again so the but that was the other thing you'll see that number will decrease as people start to close as well so it's quite nice you get to the real on the this of the mass of the real-time updates and so the example this this could be a very simple and tilted to to show people how many other people are looking at what page which perhaps could provide for mode because you know it's like 20 people over here this hotel between now and this 1 website on the and on the 1 thing I should know about WebSocket so when somebody close is the time and the next time we try and send data to the WebSocket you actually an exception which is something like WebSocket closed to that's when you break out valued and that's when the final is called so we never close let's OK on the client and the server side that's only ever done on the client side and then something just handles them exception as a light and of request that thing it doesn't it doesn't treatise narratives like you were done good and and then just for completeness this is a JavaScript I wrote and it's this kind of horrible but it turns out that it
quite hard to do you something very concisely who had been JavaScript when you want to deal with the
WebSockets and I'm not really get talk through this I mostly added so that it was stumbles across the slides involved mostly complete example that to work with and I had to have all code and doubt repositories of anyone's interested I can link it to I forgot to add that link to my slides and that is pretty easy to find and the why some really exciting and really fun about watching this is the full thing is only the ones research the 5 lines of code so that's the Python the HTML JavaScript that recruit conflict which is In metabolize but creating something like this was was fine but also you can see the path of how this could be useful even though it's such a show example to right of course with something like WebSockets the complexity comes at the next stage is what you do with this so say for example of every what something was making a request from the database you could potentially be in danger of eluding your database with connections and so on her recruit and so in the reactor I'm using something for on my mind on taller than not this 1 and then uses a horror compose grows and I'm on 1 cheaper to use so you make get 20 connections or something and so it's very easy to have too many what of something the run out connections and beating get around these problems using things like PG bouncer 1st as answer and have are running on each of your diners which then you have say 100 connections or so which only translate into 1 or 2 real connections and badly that that's just an example but be are so this is a very simple 1 but you will find that the complex those come later and and
as the and I'm not gonna read through the condition something by dissolves highway police of the common features of people asking is like the something of this doesn't have this so just to quickly mention plus use of their and these are very likes last class these fees so this means that rather than having our standard function to handle your request you can have a class which breaks out your post and the other types requests and which is quite nice way of doing it and there are blueprints and these are again very much like fast blueprints and you can see that they're actually saying something documentation that they are flask like think so they they really are trying to mimic the fast API were make sense as the blueprints are a way for you to write reusable apps which can then be added on 10 points so and cannot explain the this for making reusable and without all components to go power that's and is also unknown opinionated configuration which more prize motorways of loading up the config essentially acts like a dictionary so it's easy to store confocal you want and then disposable for things like cookies and so on everything of expect so when it comes to testing you need another optional dependency so this is the I O K http which as far as I'm aware is the most common of and HTTP requesting based in Cairo library so essentially it's is of the form of their request so this entire and although I did hear the request can have the basic compatible so part added at some point but under 1 umbrella for now this is the most popular and and signing uses internally to make requests to itself which allows you to then texture them as my understanding and this is a very simple example of how we how you use it and really testing something is simple because your son players such a narrow layer in Europe that the challenge is I found testing Russian much harder in general when using amazing so I'm not just because so when you have all your code expects to be run on a so that means essentially your tests have to set up an event you run it once and then down again i which is quite overhead for each of your tests and so even if your test misbehave so for example they don't shut down the valley properly for some reason then you the test which is blocking causes waiting is going to develop this stuff open and and it yeah so something we really interested and and this is going to request out and anyone else that knows about this is some info on how to best test is in Cairo or asynchronous at and just in general solution that talking now about post of some fish that was my request but is that not fall on some itself of things just more inherent complexity of your of roles of architecture as it changes this is just a small amount so this is something that I missed when I 1st was using something can be greatly impacts the performance so the the thing should be working on this slide is the workers equals 8 so if you don't provide a psychologist people to 1 word and 1 means is they will spawn of multiple processes and which will then review requests across the processes and handle them so obviously major factor a lot faster and so this is quite similar to something like uniform rituals spin not state multiple gender war flask processes and written request but then was signed you have essentially an event loop in each request sorry in each process so you for multiple that's going on and you should be able to acquire a lot of throughput during and the the documentation of the site developers of space into to recommend 1 what per-CPU you want to dedicate to and so the idea of focal machine give all 4 course use for workers or you might have some and their simulated to the how the ecosystem is probably the biggest sacrifice you make if you were to have in this direction compared with using some of the more established framework so there is a small that resembles that of the stations listed in the summer confrontation that seems to be the best of collection of them and build it does feel like your mileage will vary along an and more often than not you end up having to roll your integration and so there was us alive tried a few assigning limiter which is a rate limit and that's into work pretty well that I tried to another 1 to do this session handling energy that didn't work well for me because if they didn't provide back and I needed so the writing where such a handling which is this kind of thing but can really I should probably reply out and release size up you know like a of something which grows sessions or something but not on the idea that they're not interested I could look into the and then there is you don't have to start looking at how you wouldn't way with other systems so much 1st there's the times is not a surprise of using and and the thing with others is need to make using a non-blocking libraries are the most common 1 is a G. and and it nicely provides of integration with SQL coming so that allows you to use welcome you with a non-blocking connection but it only allows us to use certain parts of itself mistakenly can only use the the the core API you cannot use the oracle um so people familiar with this welcome you probably people tend to use 1 of the other things you don't tend to me both I I used the or em API and until a starting this and I had to use it for a year and the bullet point there's just no it's just a pain the you have to be aware of what you can and can't use them otherwise you run into some trouble so I think is kind of interesting thing about when should you you consider using something and sort what'll title has to do with where that's why don't I don't think people should really be looking at building a large whether something you would think more about high from food services something you need to really fast and all something like a marker so this would work really well so it's something this point light weight as lots of requests or the smaller the work and it's not city can do a larger whether of think it's just you when you start to require things like sessions and the start of the role urine in you need all of emotions many authentication packages of the it just becomes a lot work so maybe as ecosystem grows and maybe become more like fast we can just add these extensions in the becomes almost like a full spectrum that afternoon I think it was quite well as of discrete small services the and I just want to know the other options are available and and this is something which is a bit just to explain that I think a project that we should be keeping an eye on as you recall so this is the this is by Tom crystal is the author of the generous framework so he is very well experienced in this kind of error and and the user cost is and do all of G foreign and you really so he's essentially writing and they sink I version of 2 uniform that using UV light problems standards it's entirely and this will then use the AD-SDI interface rather than the WSJ interface which is a standard web server do into 4 issues by fasting giant evidence and the reason this is so important is all those so something for example it kind of has to mangle racing car on top of WSJ I would never designed for instance and so yeah I would to check you recall and I know it's not know already an ontology tree to the couple days OK so assume that it is not ready for prime time but I think it's definitely a promising option for the future and with that of course I think that actually for questions which is good because I'm most of time so much we have time for questions a few good few months it went and love and all the the did you try manage the success of configuring WebSockets secure yes so that the example I had was that using WebSockets secure subgroup remains magically maybe at truncation CPS for me and and it's using so you can see that in the top
line there it says the figures out whether it should use WSS sort of US as a particle for the what's of the collection they have rules some of some of the most that they seem to just work which is going to happen I had very little to do with the initial of personal finance but do that configuration classified for and who was aware who provide the certificate and so because I I run on a refusal handled forming and OK in the and this is but the the yeah
so maybe um you'd be standing over for example a year later he forced you arrive and no not necessary for speed of piety tried in the BIO 50 the which is 1 of the ideas of the more popular frameworks and it so I I only experimented with a for a short time and I think he was problem or just the API and I'm not sure how similar is um I did a nephritic our member the comparison well enough now to common really but I just found it didn't enjoy as much perhaps is the best way for it wasn't as easy started from the so you will because vol or maybe the common work more for common so the you feel that we are getting too many frameworks or maybe we should focus for example of the library so every other framework doesn't have you know be mistakes of every other framework the plan I I guess some of in the other for intermediate allowing our system of yes and no I I do think this is why Thomas project unicorn is important because it's implementing the base layer and I think a more correct way and then maybe time something like something could move to that and then hopefully they could then remove a bunch of nastiness they've had to do them and maybe they're the city he could do the same so the idea is that sort safe as I think also there is a lot of innovation going on at the moment so it's important for people to experiment in different ways by think over time we will start to converse together and hopefully thanks you know the and and how do you deal with a lot in a synchronous environment as the question I'm not sure if there's any particular um have not done anything to do especially if it's got I'm gonna be need to check my logins now working perspective melodies working at the the and actually try to answer it maybe you can actually break people need to request thinking we request that you could call a lot so they can actually combine with the oldest all connected in and from the other England the thank you yeah but the I can answer the 1 regard goal as so something has the little girl slogan just for looking library and the blogging in the meat and of the particle if you don't wait and it's very hard to overwrite the different over a chart thinking and failed and what also passed the configuration of little girl like and from the peak of that's also used by all the upper complications and could figure from from the go-go from that it's the same this in the good this will move because few