displaying output in html with a python code - python

I'm still learning the ins and outs of python and my goal right now is I want to display the outputs of my python code into a html webpage. How can I do that, provided that I already have a html webpage, but instead of the output displaying on the webpage itself, it displays on the console only.
app = Flask(__name__)
__author__ = 'kai'
from flask import Flask, render_template, request
import urllib.parse
import requests
#app.route('/')
def index():
return render_template('index.html')
#app.route('/hello', methods=['POST'])
def hello():
while True:
orig = request.form['starting']
if orig == "quit" or orig == "q":
break
dest = request.form['destination']
if dest == "quit" or dest == "q":
break
url = main_api + urllib.parse.urlencode({"key": key, "from": orig, "to":dest})
print("URL: " +(url))
json_data = requests.get(url).json()
json_status = json_data["info"]["statuscode"]
if json_status == 0:
print("API Status: " + str(json_status) + " = A successful route call.\n")
print("=============================================")
print("Directions from " + (orig) + " to " + (dest))
print("Trip Duration: " + (json_data["route"]["formattedTime"]))
print("-----------------Distance in different units-----------------")
print("Kilometers: " + str("{:.2f}".format((json_data["route"]["distance"])*1.61)))
print("Miles: " + str(json_data["route"]["distance"]))
print("Yards: " + str("{:.2f}".format((json_data["route"]["distance"])*1760)))
print("-----------------Fuel Used in different units-----------------")
print("Fuel Used (Ltr): " + str("{:.2f}".format((json_data["route"]["fuelUsed"])*3.78)))
print("Fuel Used (US Gal): " + str(json_data["route"]["fuelUsed"]))
print("Fuel Used (Imperial Gal): " + str("{:.2f}".format((json_data["route"]["fuelUsed"])*0.8327)))
print("=============================================")
for each in json_data["route"]["legs"][0]["maneuvers"]:
print((each["narrative"]) + " (" + str("{:.2f}".format((each["distance"])*1.61) + " km)"))
print("=============================================\n")
elif json_status == 402:
print("**********************************************")
print("Status Code: " + str(json_status) + "; Invalid user inputs for one or both locations.")
print("**********************************************\n")
elif json_status == 611:
print("**********************************************")
print("Status Code: " + str(json_status) + "; Missing an entry for one or both locations.")
print("**********************************************\n")
else:
print("************************************************************************")
print("Try Again")
print("************************************************************************\n")
if __name__ == '__main__':
app.run(host = '0.0.0.0', port = 3000)

Related

The Raspberry Pi screen cannot show the real-time numerical value received by UART communication

Send eight numerical values from Arduino to Raspberry Pi. On serial1.py, real-time numerical values appear well in the terminal. However, in the UI.py, the print(serial_result) value that comes out when the button is pressed is the old value, not the real time value. For example, if you increase the humidity, you will get a higher value after 20 seconds to 3 minutes. I want to see the correct real-time value even after pressing the button on UI.py. Attach the serial1.py and UI.py codes.
import sys
import rain
import serial1
import dust_api
import dust
import rain_forecast
from PyQt5 import QtWidgets, uic
from PyQt5.QtWidgets import QMainWindow
import set_address
form_class = uic.loadUiType("main.window.ui")[0]
# 화면을 띄우는데 사용되는 Class 선언
class WindowClass(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.fontSize = 10
# 버튼에 기능을 연결하는 코드
self.weather_button.clicked.connect(self.set_weather_dust)
# self.weather_button_2.clicked.connect(self.set_weather_rain)
# self.weather_button_3.clicked.connect(self.set_weather_th)
# self.weather_button_4.clicked.connect(self.set_weather_CO)
# self.address_button.clicked.connect(self.set_address)
def set_weather_dust(self):
serial_result = serial1.serial_check()
result = dust_api.dust_check()
print(serial_result)
dust_in = dust.dust_check_in(float(serial_result[4]))
self.textEdit.setText(
"실내 온도 : " + (serial_result[0]) + " ºC \n" + "실내 습도 : " + serial_result[
1] + " % \n" + "실내 미세먼지 : " + dust_in)
self.textEdit_2.setText("지금 실외 미세먼지 센서 수치는? " + (serial_result[5]) +
" ㎍/㎥ " + "<" + dust.dust_check_out(float(serial_result[5]))
+ ">" + "\n선택한 지역의 미세먼지 API 수치는? \n" +
"(" + result["sidoName"] + " " + result["stationName"] + ") " +
"pm10수치 : " + result["pm10수치"] + " ㎍/㎥" + " <" +
result["10형태"] + "> " + "pm2.5수치 : " + result["pm2.5수치"]
+ " ㎍/㎥ " + " <" + result["2.5형태"] + ">")
self.textEdit_3.setText("지금 실내 미세먼지 센서 수치는? " + (serial_result[4]) + " ㎍/㎥ " + "< " + dust_in + ">")
serial1.py
from collections import defaultdict
import serial
ser = serial.Serial('COM9', 9600)
def serial_check():
while True:
try:
f = str(ser.readline().decode("utf-8").strip())
except:
continue
data_list = f.split(',')
# print(f)
keys = []
values = []
# print(data_list)
if len(data_list) == 8:
for data in data_list:
values.append(str(data))
# del ser
# print(values)
return values
else:
continue
if __name__ == '__main__':
serial_check()

How to fix KeyError in python --> KeyError: 'message'?

This error usually should not appear, but recently when I run this, this error appears, and I have no clue how I will fix it.
Please if Anyone can help me to fix this error on this code below:
import requests
import json
from time import sleep
global OFFSET
OFFSET = 0
botToken = ""
global requestURL
global sendURL
requestURL = "http://api.telegram.org/bot" + botToken + "/getUpdates"
sendURL = "http://api.telegram.org/bot" + botToken + "/sendMessage"
def update (url):
global OFFSET
try:
update_raw = requests.get(url + "?offset=" + str(OFFSET))
update = update_raw.json()
result = extract_result(update)
if result != False:
OFFSET = result['update_id'] + 1
return result
else:
return False
except requests.exceptions.ConnectionError:
pass
def extract_result (dict):
result_array = dict['result']
if result_array == []:
return False
else:
result_dic = result_array[0]
return result_dic
def is_callback (dict):
if 'callback_query' in dict:
return True
def send_message (chatId, message):
requests.post(sendURL + "?chat_id=" + str(chatId) + "&text=" + message)
def send_message_button (chatId, message, buttonJSON):
requests.post(sendURL + "?chat_id=" + str(chatId) + "&reply_markup=" + buttonJSON + "&text=" + message)
#print (sendURL + "?chat_id=" + str(chatId) + "&reply_markup=" + buttonJSON + "&text=" + message)
while True:
newmessage = update (requestURL)
if newmessage != False:
if is_callback(newmessage) == True:
userchatid = newmessage['callback_query']['message']['chat']['id']
usertext = newmessage['callback_query']['message']['text']
username = newmessage['callback_query']['message']['chat']['first_name']
callback_data = newmessage['callback_query']['data']
send_message (userchatid, "Callback from " + callback_data + ", pressed by " + username)
else:
userchatid = newmessage['message']['chat']['id']
usertext = newmessage['message']['text']
username = newmessage['message']['chat']['first_name']
if usertext.lower() == "button":
buttonDict1 = {"text":"Knopf\n" + "hitest", "callback_data":"Knopf"}
buttonDict2 = {"text":"Knopf2", "callback_data":"Knopf2"}
buttonArr = {"inline_keyboard":[[buttonDict1, buttonDict2]]}
send_message_button (userchatid, "Hi " + username, json.dumps(buttonArr))
else:
send_message(userchatid, "You said: " + usertext)
sleep (1)
This is the error that appears to me after I run this bot
Line: 67
userchatid = newmessage['message']['chat']['id']
KeyError: 'message'
You catch the requests.exceptions.ConnectionError but don't handle it ( in the update function ), so now update does not return False as it returns nothing at all and can pass your check and cause havock.
Try to deal with the exception, or at least put a print in there to see if it's the one causing you issues, good luck!

Key Error 'Main' when trying an openweathermap python api tutorial

I'm currently trying to run through a tutorial of how to set up openweathermap via Python but i'm getting a KeyError and I was wondering if someone could help me out.
The error I am getting is KeyError: 'main'
In the actual code I have put in my API but have taken it out for obvious reasons.
api_key = ""
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city_name = input("Enter city name : ")
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url)
x = response.json()
if x["cod"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_pressure = y["pressure"]
current_humidiy = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
print(" Temperature (in kelvin unit) = " +
str(current_temperature) +
"\n atmospheric pressure (in hPa unit) = " +
str(current_pressure) +
"\n humidity (in percentage) = " +
str(current_humidiy) +
"\n description = " +
str(weather_description))
else:
print(" City Not Found ")
The following works:
import requests
OPEN_WEATHER_MAP_APIKEY = '<your key>'
def get_weather_data_by_location( lat, long):
url = f'https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={long}&appid={OPEN_WEATHER_MAP_APIKEY}&units=metric'
print(f"Getting data via {url}")
r = requests.get(url)
return r.json()
if r.status_code == 200:
return r.json()
else:
return None
if __name__ == '__main__':
print("Getting Weather Data")
print( get_weather_data_by_location( '22.300910042194783', '114.17070449064359') )
I have an beginners guide to open weather map which you can follow here: https://pythonhowtoprogram.com/get-weather-forecasts-and-show-it-on-a-chart-using-python-3/

Python 3.7: How to get the Windows user Login Time?

I am trying to get the System User's Login Time using Python 3.7. I have tried win32net and platform module for Python but, functions are not defined in platform module and Win32net is not compatible with Python 3 and more. I have tried following code:
import platform
platform.uname()
import platform
os_name = platform.uname()[0].lower()
if os_name == "windows":
get_win_login_time()
elif os_name.endswith("nix"):
get_nix_login_time()
Try These ( install win32com.client and subprocess modules first ):
import win32com.client, time
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("SELECT * FROM Win32_NetworkLoginProfile")
def Convert_to_human_time(dtmDate):
strDateTime = ""
if dtmDate[4] == 0:
strDateTime = dtmDate[5] + '/'
else:
strDateTime = dtmDate[4] + dtmDate[5] + '/'
if dtmDate[6] == 0:
strDateTime = strDateTime + dtmDate[7] + '/'
else:
strDateTime = strDateTime + dtmDate[6] + dtmDate[7] + '/'
strDateTime = strDateTime + dtmDate[0] + dtmDate[1] + dtmDate[2] + dtmDate[3] + " " + dtmDate[8] + dtmDate[9] + ":" + dtmDate[10] + dtmDate[11] +':' + dtmDate[12] + dtmDate[13]
return strDateTime
for objItem in colItems:
if objItem.Name is not None:
print("Name: " + str(objItem.Name))
if objItem.LastLogon is not None:
print("Last Logon (Normal Format): " + str(objItem.LastLogon))
print("Last Logon (Human Readable Format): " + Convert_to_human_time(objItem.LastLogon))
if objItem.LastLogoff is not None:
print("Last Logoff (Normal Format): " + str(objItem.LastLogoff))
print("Last Logoff (Human Readable Format): " + Convert_to_human_time(objItem.LastLogoff))
if objItem.LogonHours is not None:
print("Logon Hours: " + str(objItem.LogonHours))
if objItem.LogonServer is not None:
print("Logon Server: " + str(objItem.LogonServer))
if objItem.NumberOfLogons is not None:
print("Number Of Logons: " + str(objItem.NumberOfLogons))
Another way :
from subprocess import check_output
import sys
get_result = check_output("wmic netlogin get name, fullname, lastlogon", shell=True, stderr=False)
print(get_result)
clean_result = str(get_result).lstrip("b'").rstrip("'").replace("\\r\\r\\n", "\n").replace('\n\n', '\n').split('\n')[2:-1]
for items in clean_result:
print(items.lstrip().rstrip())
Good Luck ...

Python 2.7.12 netaddr.IPNetwork AddrFormatError

Version: Python 2.7.12
OS: Ubuntu 16.04.1
Kernel: 4.4.0-31-generic #50-Ubuntu SMP
Arch: ppc64le
netaddr.IPNetwork fails with:
netaddr.core.AddrFormatError: invalid IPNetwork '9.2.0.0/16'
I have a function:
def innet2(ip, net):
print("ip: "+ip, "net: " + net)
ip = IPAddress(ip).value
print("ipnew: " + str(ip))
network = IPNetwork(net)
print("network-first: " + str(network.first))
print("network-last: " + str(network.last))
if ip >= network.first and ip <= network.last:
return True
else:
return False
If I call this function at the beginning of my program for debug purposes
and it executes properly:
if __name__ == "__main__":
FLAGS(sys.argv)
startSSH()
print ("service ssh finished")
isParamReady = False
hostsStr = ""
isChef = False
for i in range(0, 100):
time.sleep(20)
print("test: " + str(innet("9.2.132.186", "9.2.0.0/16")))
print("test2: " + str(innet2("9.2.132.186", "9.2.0.0/16")))
print("test2: " + str(innet2("10.1.3.2", "9.2.0.0/16")))
isParamReady, hostsStr, isChef = **getHostIpStr()**
break
if (isParamReady is True and isChef is True):
execCommand(hostsStr)
else:
waitOrExit()
When it is called from getHostIPStr() it generates the AddrFormatError
def getHostIpStr():
hostsStr = "-host "
isChef = False
print("namespace= " + namespace)
print("FLAGS.job_name= " + FLAGS.job_name)
print("FLAGS.network= " + FLAGS.network)
ps_pods = v1.list_namespaced_pod(namespace, label_selector="job="
+ FLAGS.job_name)
job = v1batch.list_namespaced_job(namespace, label_selector="job="
+ FLAGS.job_name)
worker_num = job.items[0].spec.parallelism
items = ps_pods.items
print("items= ", len(items))
print("worker_num= " + str(worker_num))
if (len(items) < worker_num):
return False, "", False
for i in range(0, len(items)):
podIp = items[i].status.pod_ip
print("podIp:" + podIp)
print("localIp:" + localIp)
if (i == 0 and podIp == localIp):
isChef = True
hostIPs = getIp(podIp)
net = FLAGS.network
print("len of Ips: " + str(len(hostIPs)))
for j in range(0, len(hostIPs)):
print("j: " + str(j), "hostIPs[j]: " + hostIPs[j],
"network: " + FLAGS.network)
ip = hostIPs[j];
res = innet2(ip, net)
if (res is True):
podIp = hostIPs[j]
hostsStr = hostsStr + podIp
break
if (i < len(items)-1):
hostsStr = hostsStr + ","
return True, hostsStr, isChef
I discovered my problem.
I was passing a quoted network address and IPNetwork was failing when trying to convert the octet from of ip address into decimal format because the first octet had the string quote in it.

Categories

Resources