cool hit counter DjangoChannel handles websocket links_Intefrankly

DjangoChannel handles websocket links


Key moment, the first time to deliver!

In this tutorial, we'll use the Django channel Create an application that updates the user login and logout list in real time.

Use WebSockets in Django channel The framework manages the communication between the client and the server, and whenever a user is granted login permission, the event is broadcast to every online user. Each user can automatically access the changes happening in real time on the screen without having to log back in.

Note: We recommend that you have experience with Django before you start reading this tutorial, so you should be familiar with some of the concepts of WebSockets.

tools

We need to use the following tools to create the application.

Python (v3.6.0)

Django (v1.10.5)

Django Channels (v1.0.3)

Redis (v3.2.8)

objectives

After completing this tutorial, we were able to ......

1.Adding Web Sockets to a Django project via Django Channel

2.Create a simple connection between Django and a Redis server

3.Implement basic user login authentication

4.Feedback actions are triggered via Django every time a user logs in or out

preliminary

First, create a new virtual environment independently to install some of the project's dependencies.

Then, install Django, Django Channel, and ASGI Redis, and create a new Django project and application.

Note: In the course of practicing this tutorial, we will be creating a lot of different files and folders. If you get stuck somewhere, please refer to the file structure of the project repository.

Next, download and install Redis. If your computer is a Mac, we recommend using Homebrew for the installation of.

Next, start a separate terminal to run the Redis server program. Make sure the default port number for running the program is 6379, as this port is critical when we ask Django to interact with Redis. The initialization setup is complete after updating the INSTALLED_APPS in the project settings.py file as follows.

Then configure CHANNEL_LAYERS by setting the default BACKEND and ROUTING

As needed for the experiment, Redis is used here as the backend

WebSockets 101

Typically, Django uses the HTTP protocol for client-server communication: the

1.The client sends an HTTP request to the server

2.It's up to Django to parse this request, extract the URLs from it, and pair them into a view

3. After the request is processed by the view, an HTTP response is returned to the client

Note: Unlike the HTTP protocol, the WebSockets protocol allows for bi-directional data transfer, meaning that the server can transfer data to the client without the user requesting it, whereas in the HTTP protocol only the client that sends the request will receive the response. With the use of WebSockets, the server can interact with multiple clients at the same time. In this tutorial, we use the prefix ws:// to deliver WebSockets messages, to distinguish them from http://

Note: Before you get into the pit, please quickly skimChannels Concepts the document of the

Consumers and Groups

Create the firstconsumer is used to handle the basic connection between the client and the server. A new file is created in the directory example_channel/example calledconsumers.py which reads as follows.

Consumers are paired with Django's view. Whenever a user connects to our application, it is added to the 'users' group and receives information from the server. When the client closes the connection to our application, the channel is removed from the group and the user no longer receives information from the server. Next, let's set up the route, which is almost identical to the Django URL configuration, to create a file called a routing.py under the example_channels directory and add the following code:

So we replaced urlpatterns with channel_routing and url() with route(). At this point we find that the comsumer function is already associated with WebSockets.

templates

Let's write some HTML code that can be used to transfer data to and from the server via WebSocket, recursively creating templates/example in the example_channels/example directory, and finally composing the directory "example_channels/example/templates/example". The HTML code is as follows.

Now that the client has opened a connection to the server using WebSocket, the console prints a confirmation message.

view

1.(located) atexample_channels/example/views.py file sets up a support Django view to submit the template

2.Add the URL to theexample_channels/example/urls.py In the document.

3.(located) atexample_channels/example_channels/urls.py The file also updates the URL

test (machinery etc)

The test order is as follows.

note: Can be run in two different terminal windowspython manage.py runserver –noworker harmonypython manage.py runworker, come round test (machinery etc) ports andworker Results of running the service as a stand-alone process。 Both commands can be implemented, At this point when you visit thehttp://localhost:8000/ When you do, you will see the connection information printed by the terminal as follows:

User verification

Now that we have confirmed that we can open a connection, So our next step is to solve the User verification issues。 Remember that our mission was: We need a way, Enables every user who logs into the application to see a list of all users。 Then we first need to provide a way for the user to create an account and log in。 Start by creating a simple login page, Implementation of user login with user name and password authentication。 (located) atexample_channels/example/templates/example directory to create a directory calledlog_in.html documents which reads as follows.

Then, update example_channels/example/views.py as follows.

Django's form structure supports common authentication features, and we use AutoenticForm to handle user logins. The form results in checking the user name and password submitted by the user, and then returning the user object if a valid user can be found. After logging in to a valid user object, the page is redirected to the home page so that the user can also log out of the application, so we created an out-of-view to do this, and then rolled the user object back to the login interface. The files .py updated example_channels/example/urls are as follows:

We also need a way to create new users, and just like creating a login page, create a new file called sign_up.html in the folder example_channels/example/templates/example, which creates a registration page that reads as follows:

Notice that there is a link to the registration page on the sign-in page, and there is a pointer to the sign-back page on the registration page. Add the following functions to the view:

We use another built-in form structure to create the user object After successfully determining that the form is valid, we redirect the page to the login page by importing the form structure as follows.

Update the example_channels/exaple/urls.py file again as follows.

At this point we need to create a user object. After running the server program, visit http://localhost:8000/sign_up with a browser, fill out the form with a valid username and password, and submit the data to create the first user.

Note: username michael, password johnson123

sign_up view Redirects us to thelog_in view, in that view Under we can authenticate our newly created user object。 After we log in, may test (machinery etc) New accreditation view。 Create several new user objects using the registration form, Preparing for the next part of the process。

Login Reminder

We have been able to implement the most basic authentication functionality, but we also need to display a list containing users, and we require the server to tell the user group when the user is logged in and out. Then write the consumer function to implement it and send a message immediately after the user connects or before the user disconnects. This information data includes the user's username and run status, updating the example_channels/example/consumers.py file as follows.

Note: We have added the decorator to the function, from which we can get the user object from Django. Also all information must be in serialized JSON format, so we must convert the data to a JSON string and then update the example_channels/example/templates/example/user_list.html file as follows.

On our home page, we extend the user list to hold a list of users, and we store each user's username as a data attribute, making it easy to find user records in the DOM. We've also added an event listener for WebSocket so we can handle information from the server. Whenever we receive a message, we analyze the JSON data to find the corresponding user for the specified user

element and updates the status of that user.

Since Django does not monitor whether a user is logged in or not, we need to create a simple model to implement the monitoring functionality. In the example_channels/example/models.py file, create a LoggedInUser model with a one-to-one connection to the user module.

Whenever a user logs on, the application creates a LogedInUser instance, and when the user logs out, the application deletes the instance.

When you make a schema migration, you can migrate the database to accommodate changes.

Then, in the example_channels/example/views.py file, update the user list view, which restores the user list

If a user object has an associated LoggedInUser object, then we record that the user's state is 'Online', and conversely the user object is in the 'Offline' state. We also need to add a @login_required decorator to the user list and logout views to achieve restricting access to registered users only.

At this point the user can log in or out and this triggers the server to send a message to the client, but we have no way of knowing which users have been logged when a user first logs in. Users can only see updates when another user's state changes, and this is where LoggedInUser comes into play, but we need a way to create a LoggedInUser instance when a user logs in, and then destroy it when they log out.

The Django library has a namesignals features that will broadcast notifications when specific events occur. Applications can listen for these notifications and respond according to the broadcast content, and we can use two of the more useful built-in signals (including user_logged_in and user_logged_out) to handle the behavior of LoggedInUser. Create a new file signals.py in the example_channels/example directory with the following contents.

We should get these signals in the application configuration by configuring the example_channels/example/apps.py file as follows.

Update the example_channels/example/__init__.py file as follows.

Correctness check

Now that we're done coding, Get some users to connect to our server, thereby test (machinery etc) Our Applications。

movementDjango server, User login and access to home page。 We can see the list containing all the users in the application, All other users are in’offline’ statuses。 Then a new anonymous window opens, Login as a different user, As soon as that user logs into the browser, the user's status is’Online’。 From the anonymous window, We can also see that the user who just logged in is also in’Online’ statuses。 We can log out by having different users log in on different devices test (machinery etc)WebSockets Robustness of the。

By watching the development console messages on the client side and being able to see the server running on the terminal. We can confirm that the WebSockets connection is formed when the user logs in and is destroyed when the user logs out.

Note: You can use thengrok Host your local server securely on the Internet. This way you can access the local server using different mobile devices like phones, tablets, etc.

concluding remarks

This tutorial covers a lot of things, including Django Channels, WebSockets, user authentication, signals, and some front-end development knowledge. The main idea is to illustrate that Channels extends the functionality of traditional Django applications by being able to push information from the server to multiple groups of users via WebSockets. It is very powerful.

Think of some of these applications, for example we can create chat rooms, create multiplayer games, create collaborative applications that enable users to communicate in real time. We can even use WebSockets to optimize some routine tasks, e.g., the server will send status updates to the client after completing a task, rather than checking the server every now and then to see if a long-running task has completed.

This tutorial just picks up on some of the simple uses of Django Channel, check out the Django Channel documentation to see what else can be done.

Readers can learn more from thehttps://github.com/realpython/django-example-channels The repository gets the final code for the project. Bye-bye!!!

From: python programmer

Translated by thwcww

Original in English: https://realpython.com/blog/python/getting-started-with-django-channels/

Published by Python Development, please contact the author for permission to reprint


Recommended>>
1、Recommend a good database SDKdeepsql
2、Learn PS from scratch take you to know the basic operation of PS
3、Leaders of Jilin Provincial Procuratorate visit Green Park for research work
4、One Calls honorary qualification award clips in recent years
5、Hangzhou Mayor Xu Liyi Visited Zhejiang University of Technology Yuhang Institute of Intelligent Manufacturing Technology and Equipment

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号