In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to use Django to generate temperature dynamically and randomly and display it in real time at the front end." interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to use Django to generate temperature dynamically and randomly and display it in real time at the front end."
Catalogue
Randomly generate temperature front-end dynamic real-time
1. Django APScheduler scheduled tasks
Brief introduction
Installation
Use steps
Basic component
II. Dwebsocket
Brief introduction
Installation
Usage
Properties and methods
To simulate a random temperature display, the data in the table in models
Views
Routin
Code in VUE
Randomly generated temperature front-end dynamic real-time I. brief introduction of django APScheduler timing tasks
The full name of APScheduler is Advanced Python Scheduler.
It is a lightweight Python timed task scheduling framework.
APScheduler supports three scheduling tasks:
Fixed time interval
Fixed point in time (date)
The Crontab command under Linux.
At the same time, it also supports asynchronous execution and background execution of scheduling tasks.
Steps to install pip install APScheduler
Create a new schedulers (scheduler).
Add a scheduled task (job stores).
Run the scheduling task.
Basic component
APScheduler has four components, namely: scheduler (scheduler), job storage (job store), trigger (trigger), actuator (executor).
Schedulers (scheduler)
It is a task scheduler and belongs to the controller role. It configures job storage and executors that can be done in the scheduler, such as adding, modifying, and removing jobs.
Triggers (trigger)
Describes the conditions under which the scheduling task is triggered. But triggers are completely stateless.
Job stores (Job memory)
Task persistence warehouse, save the task in memory by default, or save the task in various databases. The data in the task is serialized and saved to the persistent database, and then deserialized after loading from the database.
Executors (actuator)
Responsible for handling the running of jobs, which are usually done by submitting a specified callable object to a thread or to a city pool in the job. When the job is completed, the executor will notify the scheduler.
7 schedulers
BlockingScheduler
The scheduler runs in the main thread of the current process, which blocks the current thread.
BackgroundScheduler
The scheduler runs in the background thread and does not block the current thread.
AsyncIOScheduler
Used in conjunction with the asyncio module, an asynchronous framework.
GeventScheduler
Gevent (high-performance Python concurrency framework) is used as the IO model in the program, which is used in conjunction with GeventExecutor.
TornadoScheduler
The IO model of Tornado (a web framework) is used in the program, and ioloop.add_timeout is used to complete the regular wake-up.
TwistedScheduler
Cooperate with TwistedExecutor, use reactor.callLater to complete regular wake-up.
QtScheduler
Your application is a Qt application, you need to use QTimer to complete regular wake-up.
II. Brief introduction of dwebsocket
WebSocket realizes the full-duplex communication between the browser and the server, and expands the communication function between the browser and the server, so that the server can actively send data to the client.
How to install pip install dwebsocket
If you want to handle a websocklet connection for a separate view, you can use the accept_websocket decorator, which routes standard HTTP requests to the view. Using the require_websocke decorator allows only WebSocket connections and rejects normal HTTP requests.
Properties and methods
1.request.is_websocket ()
If it is a websocket request that returns True, and if it is a normal http request that returns False, you can use this method to distinguish them.
2.request.websocket
After a websocket request is established, the request will have a websocket attribute that provides a simple api communication to the client. If request.is_websocket () is False, this attribute will be None.
3.WebSocket.wait ()
Returns a message sent by a client that does not return any value until the client closes the connection, in which case the method returns None
4.WebSocket.read ()
If no new message is received from the client, the read method returns a new message, and if not, it does not return. This is a non-blocking alternative to wait
5.WebSocket.count_messages ()
Returns the number of message queues
6.WebSocket.has_messages ()
Return True if there is a new message, otherwise return False
7.WebSocket.send (message)
Send messages to the client
8.WebSocket.promotional iterators _ ()
Websocket iterator
Ok, now let's get into the project.
To simulate the random temperature display, the data from django.db import models# Create your models here.class Temperature (models.Model) in the table in models: wendu = models.IntegerField () add_time = models.DateTimeField (auto_now_add=True) class Meta: db_table='temperature'viewsfrom django.shortcuts import render,HttpResponsefrom dwebsocket.decorators import accept_websocketfrom apscheduler.schedulers.background import BackgroundSchedulerfrom. Models import * import randomimport datetimeimport jsondef temperature (): # randomly generate temperatures between 1 and 50 Add to the temperature table data = random.randint (1Magne50) Temperature.objects.create (wendu=data) # scheduled task trilogy scheduler = BackgroundScheduler () scheduler .add _ job (temperature, 'interval') Seconds=1) scheduler.start () clients = [] # use @ accept_websocket decorator @ accept_websocketdef websocket_conn (request): # in websocket to get connection if request.is_websocket: # New user connection information clients.append (request.websocket) # listens to receive messages sent by the client or the client disconnects the connection for message in request. Websocket: break # send message def websocketMsg (client Msg): B1 = json.dumps (msg,ensure_ascii=False) .encode ('utf-8') client.send (b1) # the server sends a message def send (): if clients: for i in clients: wendu = Temperature.objects.order_by ('-id'). First () websocketMsg (I {'wendu': wendu.wendu}) return HttpResponse ("ok") # scheduled task 1 second / time scheduler = BackgroundScheduler () scheduler.add_job (send,'interval',seconds = 1) scheduler.start () routing from django.urls import pathfrom. The current temperature of the code in import viewsurlpatterns = [path ('websocket_conn/',views.websocket_conn)] VUE is: {{wendu}} import axios from' axios'export default {data () {return {wendu:0}} Methods: {getWenDu () {var socket = new WebSocket ("ws:127.0.0.1:8000/user/websocket_conn/") Socket.onopen = function () {console.log ('connected successfully'); / / successfully connected to Websocket}; socket.onmessage = (e = > {let data = JSON.parse (e.data)) / / data returned by the print server this.wendu = data ['wendu'] console.log (data [' wendu'])}) socket.onclose=function (e) {console.log (e); socket.close (); / / close TCP connection} }, created () {this.getWenDu ()}}
The effect is as follows:
And then we write an interface to show the temperature change for 10 seconds.
Class TestAPIView (APIView): def get (self,request): # current time now = datetime.datetime.now () # shows the temperature 10 seconds ago datelist = [] wendulist = [] for i in range: start_time = datetime.datetime.strftime (now-datetime.timedelta (seconds=i) "% Y-%m-%d% H:%M:%S") # current time end_time = datetime.datetime.strftime (now-datetime.timedelta (seconds=i-1), "% Y-%m-%d% H:%M:%S") # end time # get the temperature wendu = Temperature.objects.filter (add_time__gte=start_time) before the end time after the start time Add_time__lte=end_time) .all () dict = {} for i in wendu: dict ['wendu'] = i.wendu for kpen v in dict.items (): wendulist.append (v) # print (wendulist) datelist.append (start_time) return Response ({' datelist':datelist,'wendulist':wendulist})
In this way, we get the data as follows
Finally, we use echarts to render the final effect on the front end.
The current temperature is: {{wendu}} import axios from 'axios'import * as echarts from' echarts' Export default {data () {return {wendu:0, datelist: [], wendulist: []}}, methods: {/ / echarts getTest1 () {var chartDom = document.getElementById ('main'); var myChart = echarts.init (chartDom) Let option = {xAxis: {type: 'category', data: this.datelist}, yAxis: {type:' value',} Series: [{data: this.wendulist, type: 'line', smooth: true}]} MyChart.setOption (option) } / / get interface getTest () {this.axios.get ('user/test/') .then (res= > {console.log (res.data) this.datelist = res.data.datelist this.wendulist = res.data.wendulist this.getTest1 () this.getWenDu ()})} GetWenDu () {var socket = new WebSocket ("ws:127.0.0.1:8000/user/websocket_conn/") Socket.onopen = function () {console.log ('connected successfully'); / / successfully connected to Websocket}; socket.onmessage = (e = > {let data = JSON.parse (e.data)) / / data returned by the print server this.wendu = data ['wendu'] console.log (data [' wendu'])}) socket.onclose=function (e) {console.log (e); socket.close (); / / close TCP connection} }, mounted () {this.getWenDu () this.getTest () / / this.getTest1 ()}}
At this point, I believe you have a deeper understanding of "how to use Django to dynamically randomly generate temperature and display it in real time at the front end". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.