У меня работает сервер Flask и работает многопроцессорный цикл. я хочу иметь возможность изменять переменную на сервере фляг и просматривать ее в цикле в операторе if. вот мой код, я удалил много вещей, которые, по моему мнению, не было важно показывать.
переменная, которую нужно изменить, - это toggle (должна быть только 1 или 0)
она изменяется в sms() и используется с оператором if в цикле
# I removed a lot of stuff that i dont think was needed
import time
import math
from pyicloud import PyiCloudService
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
from math import sin, cos, sqrt, atan2, radians
from twilio.rest import TwilioRestClient
from multiprocessing import Process, Value
from flask import Flask, request
from twilio import twiml
import os
#os.system('clear')
app = Flask(__name__)
sent = 0 #only needed for loop
toggle = 0 # this is the varable that needs to be changed and viewed
def distance(x):
#returns distance in miles or km
@app.route('/sms', methods=['POST'])
def sms():
global toggle
#command replys
error = 'You did not enter a valid command'
on = 'Automatic tracker has been turned on.'
already_on = 'The automatic tracker is already on.'
off = 'Automatic tracker has been turned off.'
already_off = 'The automatic tracker is already off.'
toggle_error = 'There was a changing the status automatic tracker.'
status0 = 'The automatic tracker is currently off.'
status1 = 'The automatic tracker is currently on.'
status_error = 'There was a error checking the status of the automatic tracker.'
message_body = request.form['Body'] # message you get when sending a text to twilio number ex. i send "On" to the number and message_body will = "On"
resp = twiml.Response() # what twilio will send back to your number
if message_body == "on" or message_body == "On": #turn on automatic tracker
if toggle == 0: #set toggle to 1
toggle = 1
resp.message(on)
print on
time.sleep(3)
elif toggle == 1: #say toggle is on
resp.message(already_on)
print already_on
time.sleep(3)
else: #say toggle_error
resp.message(toggle_error)
print toggle_error
time.sleep(3)
elif message_body == "off" or message_body == "Off": #turn off automatic tracker
if toggle == 1: #set toggle to 0
toggle = 0
resp.message(off)
print off
time.sleep(3)
elif toggle == 0: #say toggle is off
resp.message(already_off)
print already_off
time.sleep(3)
else: #say toggle_error
resp.message(toggle_error)
print toggle_error
time.sleep(3)
elif message_body == "status" or message_body == "Status": #return status of automatic tracker
if toggle == 1: #say toggle is on
resp.message(status1)
print status1
time.sleep(3)
elif toggle == 0: #say toggle is off
resp.message(status0)
print status0
time.sleep(3)
else: #say status_error
resp.message(status_error)
print status_error
time.sleep(3)
else: #say invalid command
resp.message(error)
print error
print " "
time.sleep(3)
return str(resp)
print " "
def record_loop(loop_on):
while True:
global sent
global toggle
if toggle == 1: #toggle does not read as 1 when changed in sms()
if distance(2) < 2.5:
if sent == 0:
print "CLOSE"
print "sending message"
print distance(2)
client.messages.create(
to="phone number to send to", #I removed the 2 numbers
from_="twillio number", #I removed the 2 numbers
body= "CLOSE!",
)
sent = 1
else:
print "CLOSE"
print "not sending"
print distance(2)
else:
print "not close"
print distance(2)
sent = 0
else:
print 'toggle is off'
print toggle
time.sleep(1)
print " "
time.sleep(20)
if __name__ == "__main__":
recording_on = Value('b', True)
p = Process(target=record_loop, args=(recording_on,))
p.start()
app.run(use_reloader=False)
p.join()
Подробнее здесь: https://stackoverflow.com/questions/400 ... ssing-loop
Редактирование и чтение переменной между сервером Flask и многопроцессорным циклом [дубликат] ⇐ Python
Программы на Python
1763239966
Anonymous
У меня работает сервер Flask и работает многопроцессорный цикл. я хочу иметь возможность изменять переменную на сервере фляг и просматривать ее в цикле в операторе if. вот мой код, я удалил много вещей, которые, по моему мнению, не было важно показывать.
переменная, которую нужно изменить, - это toggle (должна быть только 1 или 0)
она изменяется в sms() и используется с оператором if в цикле
# I removed a lot of stuff that i dont think was needed
import time
import math
from pyicloud import PyiCloudService
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
from math import sin, cos, sqrt, atan2, radians
from twilio.rest import TwilioRestClient
from multiprocessing import Process, Value
from flask import Flask, request
from twilio import twiml
import os
#os.system('clear')
app = Flask(__name__)
sent = 0 #only needed for loop
toggle = 0 # this is the varable that needs to be changed and viewed
def distance(x):
#returns distance in miles or km
@app.route('/sms', methods=['POST'])
def sms():
global toggle
#command replys
error = 'You did not enter a valid command'
on = 'Automatic tracker has been turned on.'
already_on = 'The automatic tracker is already on.'
off = 'Automatic tracker has been turned off.'
already_off = 'The automatic tracker is already off.'
toggle_error = 'There was a changing the status automatic tracker.'
status0 = 'The automatic tracker is currently off.'
status1 = 'The automatic tracker is currently on.'
status_error = 'There was a error checking the status of the automatic tracker.'
message_body = request.form['Body'] # message you get when sending a text to twilio number ex. i send "On" to the number and message_body will = "On"
resp = twiml.Response() # what twilio will send back to your number
if message_body == "on" or message_body == "On": #turn on automatic tracker
if toggle == 0: #set toggle to 1
toggle = 1
resp.message(on)
print on
time.sleep(3)
elif toggle == 1: #say toggle is on
resp.message(already_on)
print already_on
time.sleep(3)
else: #say toggle_error
resp.message(toggle_error)
print toggle_error
time.sleep(3)
elif message_body == "off" or message_body == "Off": #turn off automatic tracker
if toggle == 1: #set toggle to 0
toggle = 0
resp.message(off)
print off
time.sleep(3)
elif toggle == 0: #say toggle is off
resp.message(already_off)
print already_off
time.sleep(3)
else: #say toggle_error
resp.message(toggle_error)
print toggle_error
time.sleep(3)
elif message_body == "status" or message_body == "Status": #return status of automatic tracker
if toggle == 1: #say toggle is on
resp.message(status1)
print status1
time.sleep(3)
elif toggle == 0: #say toggle is off
resp.message(status0)
print status0
time.sleep(3)
else: #say status_error
resp.message(status_error)
print status_error
time.sleep(3)
else: #say invalid command
resp.message(error)
print error
print " "
time.sleep(3)
return str(resp)
print " "
def record_loop(loop_on):
while True:
global sent
global toggle
if toggle == 1: #toggle does not read as 1 when changed in sms()
if distance(2) < 2.5:
if sent == 0:
print "CLOSE"
print "sending message"
print distance(2)
client.messages.create(
to="phone number to send to", #I removed the 2 numbers
from_="twillio number", #I removed the 2 numbers
body= "CLOSE!",
)
sent = 1
else:
print "CLOSE"
print "not sending"
print distance(2)
else:
print "not close"
print distance(2)
sent = 0
else:
print 'toggle is off'
print toggle
time.sleep(1)
print " "
time.sleep(20)
if __name__ == "__main__":
recording_on = Value('b', True)
p = Process(target=record_loop, args=(recording_on,))
p.start()
app.run(use_reloader=False)
p.join()
Подробнее здесь: [url]https://stackoverflow.com/questions/40094564/editing-and-reading-a-variable-between-a-flask-server-and-a-multiprocessing-loop[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия