def main(): """Функция опрашивает API раз в час и загружает данные в бд""" startDateURL = (datetime.now() - timedelta(days=3) ).strftime("%Y-%m-%d") endDateURL = (datetime.now() - timedelta(days=1) ).strftime("%Y-%m-%d") URL = "https://www.ncei.noaa.gov/" + \ "access/services/data/v1?" + \ "dataset=local-climatological-data&" + \ "stations=72509014739&" + \ "units=metric&" + \ f"startDate={startDateURL}&endDate={endDateURL}&" + \ "format=json" # запрос к погодной api r = requests.get(URL) request_json = r.json() try: # Сохранение в переменную данных за последний доступный час last_hour_values = request_json[-1] except IndexError: # Выход тк нет данных return #получение всех данных от нужного датчика FM_15_current_day_list = [] for FM_15_values in request_json: if FM_15_values['REPORT_TYPE'] == 'FM-15': FM_15_current_day_list.append(FM_15_values) # вывод значений последнего доступного часа last_hour_values = FM_15_current_day_list[-1] current_date = datetime.strptime(last_hour_values['DATE'] + '+03:00', '%Y-%m-%dT%H:%M:%S%z') hourly_humidity = float(last_hour_values['HourlyRelativeHumidity']) hourly_temp = float(last_hour_values['HourlyDryBulbTemperature']) hourly_pressure = float(last_hour_values['HourlyStationPressure'])*25.4 db_conn = Database() try: last_date = db_conn.select(""" SELECT date FROM dashboard_weather ORDER BY date DESC LIMIT 5 """)[0][0] except IndexError: last_date = False # условие для проверки повторений if last_date != current_date: db_conn.add(""" INSERT INTO dashboard_weather (humidity, pressure, temp, date) VALUES (%s, %s, %s, %s) """, (hourly_humidity, hourly_pressure, hourly_temp, current_date)) db_conn.close()
import time import Adafruit_DHT from db_conn import Database DHT_SENSOR = Adafruit_DHT.DHT22 DHT_PIN = 4 database = Database() while True: humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN) if humidity is not None and temperature is not None: database.insert_dht22(data=time.strftime('%Y-%m-%d'), hora=time.strftime('%H:%M:%S'), umidade=humidity, temperatura=temperature) else: print("falha ao coletar dados do sensor") time.sleep(60)
from tkinter import * import tkinter.messagebox as tkmsgbox from db_conn import Database import validation db = Database('contacts.db') root = Tk() root.title("Contacts") root.geometry("430x250") #=-=-=-=-=-=Frames=-=-=-=-=-=-= tops = Frame(root) tops.pack(side=TOP) bot = Frame(root) bot.pack(side=BOTTOM) #=-=-=-=-=-=-Variables=-=-=-=-=-=-= fname = StringVar() lname = StringVar() mob = StringVar() email = StringVar() #=-=-=-=--=-=-=-=Functions=-=-=-=-=-=-=-= def content(): lst.delete(0, END) for row in db.fetch(): lst.insert(END, row) def select(row):
def __init__(self): self.database = Database() self.database.create_user_table()
class User: def __init__(self): self.database = Database() self.database.create_user_table() def create_user(self): """create a user account [POST]""" parser = reqparse.RequestParser() parser.add_argument('username', type=str, required=True, help='Field cannot be blank') parser.add_argument('email', type=str, required=True, help='Field cannot be blank') parser.add_argument('password', type=str, required=True, help='Field cannot be blank') data = parser.parse_args() specialCharacters = ['$', '#', '@', '!', '*'] if any(char in specialCharacters for char in (data['username'])): return {'message': 'username cannot have special characters'}, 400 elif self.find_user_by_name(data['username']): return {'message': 'user already exists'}, 409 elif self.find_user_by_email(data['email']): return {'message': 'please use another email address'}, 409 elif data['username'].isspace() or (' ' in data['username']): return {'message': 'Field cannot be blank'}, 400 elif not re.match('[^@]+@[^@]+\.[^@]+', data['email']): return {'message': 'Invalid email'}, 400 self.database.cursor.execute( "INSERT INTO users(username, email, password)\ VALUES('{}', '{}', '{}')\ RETURNING userId, username, email, password".format( data['username'], data['email'], data['password'])) return {'message': 'User created successfully'}, 201 def login_user(self): """user login [POST]""" parser = reqparse.RequestParser() parser.add_argument('username', type=str, required=True, help='Field cannot be blank') parser.add_argument('password', type=str, required=True, help='Field cannot be blank') data = parser.parse_args() if data['username'] == 'admin' and data['password'] == 'mynameisadmin': token = jwt.encode( { 'username': data['username'], 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60) }, 'adminkey') return { 'message': 'welcome admin', 'token': token.decode('utf-8') }, 200 elif self.find_user_by_name( data['username'] ) is None or self.find_user_by_password is None: return {'message': 'Please Create an account'}, 401 elif self.find_user_by_name( data['username']) == self.find_user_by_password( data['password']): token = jwt.encode( { 'username': data['username'], 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60) }, 'customerkey') return { 'message': 'You are successfully logged in', 'token': token.decode('utf-8') }, 200 return {'message': 'username or password is incorrect'}, 401 def find_user_by_name(self, username): query = "SELECT * FROM users WHERE username = '******'" self.database.cursor.execute(query.format(username)) row = self.database.cursor.fetchone() if row: return row else: return None def find_user_by_email(self, email): query = "SELECT * FROM users WHERE email = '{}'" self.database.cursor.execute(query.format(email)) row = self.database.cursor.fetchone() if row: return row else: return None def find_user_by_password(self, password): query = "SELECT * FROM users WHERE password = '******'" self.database.cursor.execute(query.format(password)) row = self.database.cursor.fetchone() if row: return row else: return None
import RPi.GPIO as GPIO import time from db_conn import Database #gpio.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(33, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(33, GPIO.RISING, bouncetime=300) database = Database() while True: if GPIO.event_detected(33): database.insert_pluviometer( data=time.strftime('%Y-%m-%d'), hora=time.strftime('%H:%M:%S'), precipitacao=2.5, )
from db_conn import Database from datetime import datetime, timedelta import random db_conn = Database() now = datetime.now() for days in range(7, 500): for hours in range(1, 2): hourly_humidity = random.randint(40, 61) hourly_pressure = random.randint(780, 891) hourly_temp = random.randint(10, 27) new_date = now - timedelta(days=days, hours=hours) db_conn.add( """ INSERT INTO dashboard_weather (humidity, pressure, temp, date) VALUES (%s, %s, %s, %s) """, (hourly_humidity, hourly_pressure, hourly_temp, new_date)) db_conn.close()
def setUp(self): """Initialisez app and defines variables""" app.testing = True self.tester = app.test_client() self.database = Database() self.database.create_user_table()
class AppTestCase(unittest.TestCase): def setUp(self): """Initialisez app and defines variables""" app.testing = True self.tester = app.test_client() self.database = Database() self.database.create_user_table() # self.database.create_menu_table() # self.database.create_order_table() # self.order = { # 'orderId': 1, 'username': '******', 'foodId': 1, 'status': 'New' # } # self.menu = { # 'foodId': 1, 'name': 'pizza', 'description': 'hawain', # 'price': 25000 # } def tearDown(self): """Crashes down all initialized variables""" # self.database.cursor.execute("DROP TABLE orders") # self.database.cursor.execute("DROP TABLE menu") self.database.cursor.execute("DROP TABLE users") self.tester = None def test_home(self): response = self.tester.get('/') self.assertTrue(200, response.status_code) self.assertIn('Welcome', str(response.data)) # def test_neworder(self): # """Tests api to place new order without token""" # response = self.tester.post('/api/v1/orders', data=self.order) # self.assertEqual(403, response.status_code) # self.assertIn('Token is missing', str(response.data)) # """Tests api to place new order with token""" # response = self.tester.post('/api/v1/menu', # data=self.menu, # headers=dict(Authorization='Bearer ' + GetToken.get_admin_token())) # response = self.tester.post('/api/v1/orders', # data=self.order, # headers=dict(Authorization='Bearer ' + GetToken.get_user_token())) # self.assertEqual(201, response.status_code) # def test_orders(self): # """Tests api to get all orders without authorization""" # response = self.tester.get('/api/v1/orders', data=self.order) # self.assertEqual(403, response.status_code) # self.assertIn('Token is missing', str(response.data)) # """Tests api to get all orders with authorization""" # response = self.tester.post('/api/v1/menu', # data=self.menu, # headers=dict(Authorization='Bearer ' + GetToken.get_admin_token())) # response = self.tester.post('/api/v1/orders', # data=self.order, # headers=dict(Authorization='Bearer ' + GetToken.get_user_token())) # self.assertEqual(201, response.status_code) # response = self.tester.get('/api/v1/orders', # data=self.order, # headers=dict(Authorization='Bearer ' + GetToken.get_admin_token())) # self.assertEqual(200, response.status_code) # def test_no_orders(self): # """test for unavailable menu""" # response = self.tester.get('/api/v1/orders', # data={}, # headers=dict(Authorization='Bearer ' + GetToken.get_admin_token())) # self.assertEqual(404, response.status_code) # self.assertIn('No orders found', str(response.data)) # def test_history(self): # """test api to get order history""" # response = self.tester.get('/api/v1/users/orders', data=self.order) # self.assertEqual(403, response.status_code) # self.assertIn(b'Token is missing', response.data) # """test api to get order history with token""" # response = self.tester.post('/api/v1/menu', # data=self.menu, # headers=dict(Authorization='Bearer ' + GetToken.get_admin_token())) # response = self.tester.post('/api/v1/orders', # data=self.order, # headers=dict(Authorization='Bearer ' + GetToken.get_user_token())) # self.assertEqual(201, response.status_code) # response = self.tester.get('/api/v1/users/orders', # data=self.order, # headers=dict(Authorization='Bearer ' + GetToken.get_user_token())) # self.assertEqual(200, response.status_code) # def test_no_order_history(self): # """test no order history""" # response = self.tester.post('/api/v1/menu', # data=self.menu, # headers=dict(Authorization='Bearer ' + GetToken.get_admin_token())) # response = self.tester.get('/api/v1/users/orders', # data=self.order, # headers=dict(Authorization='Bearer ' + GetToken.get_user_token())) # self.assertEqual(404, response.status_code) # self.assertIn('No Previous Orders', str(response.data)) # def test_get_order(self): # """Tests api to get a specific order""" # response = self.tester.get('/api/v1/orders/1', data=self.order) # self.assertEqual(response.status_code, 403) # self.assertIn('Token is missing', str(response.data)) # """Tests api to get a specific order with token""" # response = self.tester.post('/api/v1/menu', # data=self.menu, # headers=dict(Authorization='Bearer ' + GetToken.get_admin_token())) # response = self.tester.post('/api/v1/orders', # data=self.order, # headers=dict(Authorization='Bearer ' + GetToken.get_user_token())) # self.assertEqual(201, response.status_code) # response = self.tester.get('/api/v1/orders/1', # data=self.order, # headers=dict(Authorization='Bearer ' + GetToken.get_admin_token())) # self.assertEqual(response.status_code, 200) # """test non existing order""" # response = self.tester.get('/api/v1/orders/7', # data=self.order, # headers=dict(Authorization='Bearer ' + GetToken.get_admin_token())) # self.assertEqual(response.status_code, 404) # self.assertIn('The order you requested does not exist', str(response.data)) # def test_put(self): # """Tests api to edit and already existing order with token""" # response = self.tester.put('/api/v1/orders/1',data=self.order) # self.assertEqual(response.status_code, 403) # self.assertIn('Token is missing', str(response.data)) # """Tests api to edit and already existing order with token""" # response = self.tester.put('/api/v1/orders/1', data={'status': 'complete'}, # headers=dict(Authorization='Bearer ' + GetToken.get_admin_token())) # self.assertEqual(response.status_code, 200) # self.assertIn('Order status has been updated', str(response.data)) # """test update input validation""" # response = self.tester.put('/api/v1/orders/1', data={'status': ' '}, # headers=dict(Authorization='Bearer ' + GetToken.get_admin_token())) # self.assertEqual(response.status_code, 400) # self.assertIn('Field cannot be blank', str(response.data)) # def test_delete(self): # """Test api to delete an order without token""" # response = self.tester.delete('/api/v1/orders/1', data=self.order) # self.assertEqual(403, response.status_code) # """Test api to delete an order with token""" # response = self.tester.delete('/api/v1/orders/1', # data=self.order, # headers=dict(Authorization='Bearer ' + GetToken.get_user_token())) # self.assertEqual(200, response.status_code) # self.assertIn('Order has been deleted', str(response.data))