diff --git a/.gitignore b/.gitignore index 002698a..5afc140 100644 --- a/.gitignore +++ b/.gitignore @@ -1,119 +1,6 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -.hypothesis/ -.pytest_cache/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py - -# pyenv -.python-version - -# celery beat schedule file -celerybeat-schedule - -# SageMath parsed files -*.sage.py - -# Environments -.env -.venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy -.mypy_cache/ -.dmypy.json -dmypy.json - -# Pyre type checker -.pyre/ +# Created by .ignore support plugin (hsz.mobi) ### JetBrains template -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 # User-specific stuff @@ -123,6 +10,9 @@ dmypy.json .idea/**/dictionaries .idea/**/shelf +# Generated files +.idea/**/contentModel.xml + # Sensitive or high-churn files .idea/**/dataSources/ .idea/**/dataSources.ids @@ -140,9 +30,14 @@ dmypy.json # When using Gradle or Maven with auto-import, you should exclude module files, # since they will be recreated, and may cause churn. Uncomment if using # auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml # .idea/modules.xml # .idea/*.iml # .idea/modules +# *.iml +# *.ipr # CMake cmake-build-*/ @@ -155,7 +50,7 @@ cmake-build-*/ # IntelliJ out/ -.idea/ + # mpeltonen/sbt-idea plugin .idea_modules/ @@ -173,6 +68,10 @@ fabric.properties # Editor-based Rest Client .idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + ### Python template # Byte-compiled / optimized / DLL files __pycache__/ @@ -196,6 +95,8 @@ parts/ sdist/ var/ wheels/ +pip-wheel-metadata/ +share/python-wheels/ *.egg-info/ .installed.cfg *.egg @@ -214,14 +115,17 @@ pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ +.nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover +*.py,cover .hypothesis/ .pytest_cache/ +cover/ # Translations *.mo @@ -231,6 +135,7 @@ coverage.xml *.log local_settings.py db.sqlite3 +db.sqlite3-journal # Flask stuff: instance/ @@ -243,16 +148,34 @@ instance/ docs/_build/ # PyBuilder +.pybuilder/ target/ # Jupyter Notebook .ipynb_checkpoints +# IPython +profile_default/ +ipython_config.py + # pyenv -.python-version +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock -# celery beat schedule file +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff celerybeat-schedule +celerybeat.pid # SageMath parsed files *.sage.py @@ -278,6 +201,15 @@ venv.bak/ # mypy .mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ -.idea/ -requirements.txt diff --git a/example/BevzykKostiantyn/Project/Readme.md b/example/BevzykKostiantyn/Project/Readme.md new file mode 100644 index 0000000..dee859e --- /dev/null +++ b/example/BevzykKostiantyn/Project/Readme.md @@ -0,0 +1,4 @@ +1. Change connections to Oracle db in file connections.py +1.2. Download all packeges that are mentioned in requirements.txt +2. Run models_creation.py to create shemas(tables) on your local machine and to insert some data +3. Run bot.py to start telegram bot on your local machine, You can access him buy @info453_bot in Telegram diff --git a/example/BevzykKostiantyn/Project/bot.py b/example/BevzykKostiantyn/Project/bot.py new file mode 100644 index 0000000..fec1ab9 --- /dev/null +++ b/example/BevzykKostiantyn/Project/bot.py @@ -0,0 +1,206 @@ +import config +import telebot +from telebot import types +import requests +import time +from sqlalchemy.orm import sessionmaker +from sqlalchemy import func +from models_creation import User, Resources +from connections import engine +import random +import pandas as pd +import plotly.express as px +import numpy as np + +Session = sessionmaker(bind=engine) +session = Session() + + +token = config.token +api_key = config.news_token +bot = telebot.TeleBot(token) +locations = { + 'Ukraine': 'ua', + 'Russia': 'ru', + 'United Kingdom': 'uk', + 'USA': 'us' +} +loc = 'ua' +cat = 'general' +category = ['business', 'entertainment', 'general', 'health', 'science', 'technology'] +keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) +button_1 = types.KeyboardButton(text="Ukraine") +button_2 = types.KeyboardButton(text="Russia") +button_4 = types.KeyboardButton(text="USA") +keyboard.add(button_1, button_2, button_4) +keyboard_1 = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) +button1 = types.KeyboardButton(text="business") +button2 = types.KeyboardButton(text="entertainment") +button3 = types.KeyboardButton(text="health") +button4 = types.KeyboardButton(text="science") +button5 = types.KeyboardButton(text="technology") +button6 = types.KeyboardButton(text="general") +keyboard_1.add(button1, button2, button3, button4, button5, button6) + + + +def news_api(cat, loc): + url = f'https://newsapi.org/v2/top-headlines?country={loc}&category={cat}&pageSize=40&apiKey={api_key}' + try: + response = requests.get(url) + except Exception as e: + print(e) + info = response.json() + ind = 0 + ind2 = 0 + if info['totalResults'] > 4: + while ind2 - ind != 4: + ind = random.randrange(0, info['totalResults']) + ind2 = random.randrange(0, info['totalResults']) + true_info = info['articles'][ind:ind2] + for i in true_info: + yield i['title'], i['url'] + + +@bot.message_handler(commands=['start']) +def send_(message): + global register + register = 0 + bot.send_message(message.chat.id, "Hello, I am glad to see you {f}".format(f=message.chat.first_name)) + time.sleep(3) + bot.send_message(message.chat.id, 'Send me your location, so i can sort news for your destination', + reply_markup=keyboard) + + +@bot.message_handler(commands=['help']) +def send_(message): + bot.send_message(message.chat.id, "Options that you can use \n /update_location " + "\n /stop \n /update_category \n /news \n /stats") + + +@bot.message_handler(commands=['update_location']) +def send_(message): + global flag + flag = 1 + bot.send_message(message.chat.id, 'Choose your new location', reply_markup=keyboard) + global register + register = 1 + + +@bot.message_handler(commands=['stats']) +def send_(message): + q = ''' + Select count(distinct user_id) As dau, USER_DATE + from users + group by USER_DATE + ''' + + result = session.execute(q) + x = [] + y = [] + nfo = [row for row in result] + for i in nfo: + x.append(i[0]) + val = str(i[1]).split()[0] + val = np.datetime64(val) + y.append(val) + + df = pd.DataFrame({'Users': x, 'Date': y}) + df = df.groupby(by='Date', as_index=False).sum() + fig = px.line(df, x='Date', y='Users') + fig.show() + query = ''' + Select count(DISTINCT users.user_id) as amount, resources.location_ + FROM users JOIN RESOURCES ON users.user_id = RESOURCES.USER_ID + GROUP BY resources.location_ + ''' + res = session.execute(query) + nfo = [row for row in res] + x = [] + y = [] + for i in nfo: + x.append(i[0]) + y.append(i[1]) + df_1 = pd.DataFrame({'Amount': x, 'Location': y}) + fig1 = px.pie(df_1, values='Amount', names='Location', title='Amount of users slided by countries') + fig1.show() + + +@bot.message_handler(commands=['update_category']) +def send_(message): + global flag + flag = 1 + bot.send_message(message.chat.id, "Choose your new category", reply_markup=keyboard_1) + global register + register = 1 + + +@bot.message_handler(commands=['stop']) +def send_(message): + global flag + flag = 1 + bot.send_message(message.chat.id, "I have stoped, thanks for using") + try: + session.query(Resources).filter(Resources.user_id == message.chat.id).delete(synchronize_session=False) + session.commit() + session.query(User).filter(User.user_id == message.chat.id).delete(synchronize_session=False) + session.commit() + except Exception as e: + print(e) + bot.stop_polling() + + +@bot.message_handler(commands=['news']) +def sendnews(message): + chat = message.chat.id + generate_news = news_api(cat, loc) + try: + for i in range(4): + info = next(generate_news) + bot.send_message(chat, info[1]) + time.sleep(5) + except Exception as e: + print(e) + + +@bot.message_handler(content_types=['text']) +def send_mess(message): + if message.text in locations.keys(): + global loc + loc = locations[message.text] + print(loc) + if register == 0: + bot.send_message(message.chat.id, "Thanks, and now send me your favorite category", reply_markup=keyboard_1) + else: + bot.send_message(message.chat.id, "Get it") + try: + session.query(Resources).filter(Resources.user_id == message.chat.id).update({Resources.location_: loc.upper()}) + session.commit() + except Exception as e: + print(e) + elif message.text in category: + global cat + cat = message.text + print(cat) + if register == 0: + bot.send_message(message.chat.id, "You have finished, congrats! \nNow, whenever you need news \ntype /news") + try: + new_user = User(user_id=message.chat.id, user_name=message.chat.first_name, user_date=func.current_date()) + new_user_res = Resources(user_id=message.chat.id, category_=cat, location_=loc) + for i in [new_user, new_user_res]: + session.add(i) + session.commit() + except Exception as e: + print(e) + else: + bot.send_message(message.chat.id, 'Get it') + try: + session.query(Resources).filter(Resources.user_id == message.chat.id).update({Resources.category_: cat}) + session.commit() + except Exception as e: + print(e) + else: + bot.send_message(message.chat.id, "Probably you /help or /news") + + +bot.polling(none_stop=True) \ No newline at end of file diff --git a/example/BevzykKostiantyn/Project/config.py b/example/BevzykKostiantyn/Project/config.py new file mode 100644 index 0000000..2f807e4 --- /dev/null +++ b/example/BevzykKostiantyn/Project/config.py @@ -0,0 +1,2 @@ +token = '1027503335:AAE-qb2GZOo0M5WXkxXJT4chSTyoASvi-Ps' +news_token = '9ad9f03408304772a7f6ab910a34ddc3' diff --git a/example/BevzykKostiantyn/Project/connections.py b/example/BevzykKostiantyn/Project/connections.py new file mode 100644 index 0000000..cab22fb --- /dev/null +++ b/example/BevzykKostiantyn/Project/connections.py @@ -0,0 +1,12 @@ +from sqlalchemy import create_engine +oracle_connection_string = 'oracle+cx_oracle://{username}:{password}@{hostname}:{port}/?service_name={database}' + +engine = create_engine( + oracle_connection_string.format( + username="MYDATABASE", + password="qwert123", + hostname="localhost", + port='1521', + database='XE' + ) +) \ No newline at end of file diff --git a/example/BevzykKostiantyn/Project/models_creation.py b/example/BevzykKostiantyn/Project/models_creation.py new file mode 100644 index 0000000..a65f11d --- /dev/null +++ b/example/BevzykKostiantyn/Project/models_creation.py @@ -0,0 +1,112 @@ +from sqlalchemy import Column, String, Integer, ForeignKey, Date +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy import CheckConstraint +from sqlalchemy.orm import sessionmaker, relationship +from sqlalchemy import create_engine +from sqlalchemy import func, update +import plotly.express as px +import pandas as pd +import numpy as np + +oracle_connection_string = 'oracle+cx_oracle://{username}:{password}@{hostname}:{port}/?service_name={database}' + +engine = create_engine( + oracle_connection_string.format( + username="MYDATABASE", + password="qwert123", + hostname="localhost", + port='1521', + database='XE' + ) +) + + +Session = sessionmaker(bind=engine) +session = Session() +Base = declarative_base() + + +class User(Base): + __tablename__ = 'users' + user_id = Column(Integer, primary_key=True) + user_name = Column(String(40), nullable=False) + user_date = Column(Date, nullable=True) + resources = relationship("Resources") + + def __init__(self, user_id, user_name, user_date): + self.user_id = user_id + self.user_name = user_name + self.user_date = user_date + + +class Resources(Base): + __tablename__ = 'resources' + user_id = Column(Integer, ForeignKey('users.user_id'), primary_key=True) + location_ = Column(String(50), CheckConstraint('length(location_) > 0'), nullable=False) + category_ = Column(String(50), CheckConstraint('length(category_) > 0'), nullable=False) + + def __init__(self, user_id, location_, category_): + self.user_id = user_id + self.location_ = location_ + self.category_ = category_ + + +Base.metadata.create_all(engine) + +if __name__ == '__main__': + boban = User(user_id=12313, user_name="Boban", user_date=func.current_date()-1) + bobovich = User(user_id=212321, user_name="Bobovich", user_date=func.current_date()) + bobenko = User(user_id=3333, user_name="Bobenko", user_date=func.current_date()-1) + boban_res = Resources(user_id=12313, location_="Germany", category_="games") + bobovich_res = Resources(user_id=212321, location_="UK", category_="business") + bobenko_res = Resources(user_id=3333, location_='UK', category_='business') + bober = User(user_id=666, user_name="bober", user_date=func.current_date()-2) + bober_res = Resources(user_id=666, location_='ua', category_='general') + + try: + new_users = [boban, bobovich, bobenko, bobovich_res, boban_res, bobenko_res, bober, bober_res] + for i in new_users: + session.add(i) + session.commit() + except Exception as e: + print(e) + + q = ''' + Select count(distinct user_id) As dau, USER_DATE + from users + group by USER_DATE + ''' + + result = session.execute(q) + x = [] + y = [] + nfo = [row for row in result] + for i in nfo: + x.append(i[0]) + val = str(i[1]).split()[0] + val = np.datetime64(val) + y.append(val) + + df = pd.DataFrame({'Users': x, 'Date': y}) + df = df.groupby(by='Date', as_index=False).sum() + print(df) + fig = px.line(df, x='Date', y='Users') + fig.show() + query = ''' + Select count(DISTINCT users.user_id) as amount, resources.location_ + FROM users JOIN RESOURCES ON users.user_id = RESOURCES.USER_ID + GROUP BY resources.location_ + ''' + res = session.execute(query) + nfo = [row for row in res] + print(nfo) + x = [] + y = [] + for i in nfo: + x.append(i[0]) + y.append(i[1]) + df_1 = pd.DataFrame({'Amount': x, 'Location': y}) + print(df_1) + fig1 = px.pie(df_1, values='Amount', names='Location', title='Amount of users slided by countries') + fig1.show() + diff --git a/example/BevzykKostiantyn/workshop3/Readme.md b/example/BevzykKostiantyn/workshop3/Readme.md new file mode 100644 index 0000000..9443db7 --- /dev/null +++ b/example/BevzykKostiantyn/workshop3/Readme.md @@ -0,0 +1 @@ +Main file in roots Workshop3.py, run him to check my work. Thanks diff --git a/example/BevzykKostiantyn/workshop3/WorkShop2 Flask.pdf b/example/BevzykKostiantyn/workshop3/WorkShop2 Flask.pdf new file mode 100644 index 0000000..428197d Binary files /dev/null and b/example/BevzykKostiantyn/workshop3/WorkShop2 Flask.pdf differ diff --git a/example/BevzykKostiantyn/workshop3/root/Workshop3.py b/example/BevzykKostiantyn/workshop3/root/Workshop3.py new file mode 100644 index 0000000..e8592f2 --- /dev/null +++ b/example/BevzykKostiantyn/workshop3/root/Workshop3.py @@ -0,0 +1,43 @@ +from flask import Flask, render_template, request, redirect, url_for + +app = Flask(__name__) + +user_dict = { + "Name": "Kostiantyn", + "Id": "5" +} + +user_resources = { + "Category": "business", + "Location": "Germany" +} + + +@app.route('/', methods=['GET']) +def get_info(action): + if request.method == 'GET': + if action == "user_dict": + return render_template('User_dict.html', user_dict=user_dict) + elif action == "user_resources": + return render_template("User_resources.html", user_resources=user_resources) + elif action == "all": + return render_template("All.html", users=user_dict, resources=user_resources) + else: + return render_template("Error.html") + + +@app.route('//add', methods=['POST']) +def post(action): + if action == 'user_dict': + if request.form['action'] == "new_user": + user_dict["Name"] = request.form['name'] + user_dict["Id"] = request.form['id'] + return redirect(url_for('get_info', action="all")) + if action == 'user_resources': + if request.form['action'] == "new_user": + user_resources["Category"] = request.form['category'] + user_resources["Location"] = request.form['location'] + return redirect(url_for('get_info', action="all")) + + +app.run() \ No newline at end of file diff --git a/example/BevzykKostiantyn/workshop3/templates/All.html b/example/BevzykKostiantyn/workshop3/templates/All.html new file mode 100644 index 0000000..75fd740 --- /dev/null +++ b/example/BevzykKostiantyn/workshop3/templates/All.html @@ -0,0 +1,11 @@ + + + + + View + + +

Table Users : {{users}}

+

Table Their Resources: {{resources}}

+ + \ No newline at end of file diff --git a/example/BevzykKostiantyn/workshop3/templates/Error.html b/example/BevzykKostiantyn/workshop3/templates/Error.html new file mode 100644 index 0000000..25a2a42 --- /dev/null +++ b/example/BevzykKostiantyn/workshop3/templates/Error.html @@ -0,0 +1,10 @@ + + + + + 404 Not Found + + +

Take another action

+ + \ No newline at end of file diff --git a/example/BevzykKostiantyn/workshop3/templates/User_dict.html b/example/BevzykKostiantyn/workshop3/templates/User_dict.html new file mode 100644 index 0000000..1f71dfe --- /dev/null +++ b/example/BevzykKostiantyn/workshop3/templates/User_dict.html @@ -0,0 +1,15 @@ + + + + + Editor + + +
+

Name

+

Id

+
+ + + + \ No newline at end of file diff --git a/example/BevzykKostiantyn/workshop3/templates/User_resources.html b/example/BevzykKostiantyn/workshop3/templates/User_resources.html new file mode 100644 index 0000000..54f4201 --- /dev/null +++ b/example/BevzykKostiantyn/workshop3/templates/User_resources.html @@ -0,0 +1,19 @@ + + + + + client + + + + +
+

Category

+

Location

+
+ + + + + + \ No newline at end of file diff --git a/example/BevzykKostiantyn/workshop4,5/Project.sql b/example/BevzykKostiantyn/workshop4,5/Project.sql new file mode 100644 index 0000000..1ea3198 --- /dev/null +++ b/example/BevzykKostiantyn/workshop4,5/Project.sql @@ -0,0 +1,57 @@ +create table users( + user_id Integer Primary key, + user_name VARCHAR2(50) NOT NULL UNIQUE, + user_date date NOT NULL, + age Integer, + CONSTRAINT age_check CHECK (age>14) +); + +create table resources( + user_id Integer Primary key, + location_ VARCHAR2(50) NOT NULL, + category_ VARCHAR2(50) NOT NULL, + Constraint check_3 foreign key (user_id) references users(user_id) +); + + +AlTER TABLE resources ADD CONSTRAINT loc_check CHECK (length(location_)>0); + +AlTER TABLE resources ADD CONSTRAINT category_ CHECK (length(category_)>0); + + + +CREATE or Replace Trigger check_user_name +BEFORE UPDATE of user_name ON users +FOR EACH ROW +DECLARE +strin VARCHAR(50); +BEGIN +select regexp_replace(:new.user_name, '[[:alpha:]]|_') into strin from dual; +IF strin is not null then + raise_application_error(-20000, 'Wrong user name format in update!'); +END IF; +END; + +CREATE or Replace Trigger check_loc +BEFORE UPDATE of location_ ON resources +FOR EACH ROW +DECLARE +strin VARCHAR(50); +BEGIN +select regexp_replace(:new.location_, '[[:alpha:]]|_') into strin from dual; +IF strin is not null then + raise_application_error(-20000, 'Wrong user name format in update!'); +END IF; +END; + +Create or Replace Trigger check_category +BEFORE UPDATE of category_ ON resources +FOR EACH ROW +DECLARE +strin VARCHAR(50); +BEGIN +select regexp_replace(:new.category_, '[[:alpha:]]|_') into strin from dual; +IF strin is not null then + raise_application_error(-20000, 'Wrong user name format in update!'); +END IF; +END; diff --git a/example/BevzykKostiantyn/workshop4,5/README.md b/example/BevzykKostiantyn/workshop4,5/README.md new file mode 100644 index 0000000..02db883 --- /dev/null +++ b/example/BevzykKostiantyn/workshop4,5/README.md @@ -0,0 +1,2 @@ +In this workshop i worked with Oracle database. To run sqlalchemy go to Workshop4.py and run this file, +alternatively you can run Project.sql, in file Workshop4.py You need to change Oracle connection with your local machine settings. diff --git a/example/BevzykKostiantyn/workshop4,5/Workshop4,5.py b/example/BevzykKostiantyn/workshop4,5/Workshop4,5.py new file mode 100644 index 0000000..4778ed1 --- /dev/null +++ b/example/BevzykKostiantyn/workshop4,5/Workshop4,5.py @@ -0,0 +1,103 @@ +from sqlalchemy import Column, String, Integer, ForeignKey, Date +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy import CheckConstraint +from sqlalchemy.orm import sessionmaker, relationship +from sqlalchemy import create_engine +from sqlalchemy import func +import plotly.express as px +import pandas as pd +import numpy as np + +oracle_connection_string = 'oracle+cx_oracle://{username}:{password}@{hostname}:{port}/?service_name={database}' + +engine = create_engine( + oracle_connection_string.format( + username="MYDATABASE", + password="qwert123", + hostname="localhost", + port='1521', + database='XE' + ) +) + + +Session = sessionmaker(bind=engine) +session = Session() +Base = declarative_base() + + +class User(Base): + __tablename__ = 'users' + user_id = Column(Integer, primary_key=True) + user_name = Column(String(40), nullable=False) + user_date = Column(Date, nullable=True) + age = Column(Integer, CheckConstraint('age > 14', name='check_age'), nullable=True) + resources = relationship("Resources") + + def __init__(self, user_id, user_name, user_date, age): + self.user_id = user_id + self.user_name = user_name + self.user_date = user_date + self.age = age + + +class Resources(Base): + __tablename__ = 'resources' + user_id = Column(Integer, ForeignKey('users.user_id'), primary_key=True) + location_ = Column(String(50), CheckConstraint('length(location_) > 0'), nullable=False) + category_ = Column(String(50), CheckConstraint('length(category_) > 0'), nullable=False) + + def __init__(self, location_, category_): + self.location_ = location_ + self.category_ = category_ + + +Base.metadata.create_all(engine) + + +boban = User(user_id=12313, user_name="Boban", user_date=func.current_date()-2, age=15) +bobovich = User(user_id=212321, user_name="Bobovich", user_date=func.current_date(), age=17) +bobenko = User(user_id=3333, user_name="Bobenko", user_date=func.current_date()-3, age=18) +Boba = User(user_id=666, user_name="Boba", user_date=func.current_date(), age=23) +boban_res = Resources(location_="Germany", category_="games") +bobovich_res = Resources(location_="UK", category_="business") +bobenko_res = Resources(location_='LA', category_='general') +borb_res = Resources(location_="LO", category_='general') +bobenko.resources.append(bobenko_res) +boban.resources.append(bobovich_res) +bobovich.resources.append(boban_res) +Boba.resources.append(borb_res) + +try: + new_users = [boban, bobovich, bobenko, Boba] + for i in new_users: + session.add(i) + session.commit() +except Exception as e: + print(e) +session.query(Resources).filter(Resources.user_id == 12313).delete() +session.commit() +session.query(User).filter(User.user_id == 12313).delete() +session.commit() +session.query(Resources).filter(Resources.user_id == 3333).update({Resources.category_: 'general', + Resources.location_: 'ua'}) +session.commit() + +q = '''Select count(distinct user_id) As dau, USER_DATE +from users +group by USER_DATE''' +result = session.execute(q) +x = [] +y = [] +nfo = [row for row in result] +for i in nfo: + x.append(i[0]) + val = str(i[1]).split()[0] + val = np.datetime64(val) + y.append(val) + +df = pd.DataFrame({'Users': x, 'Date': y}) +print(df) +fig = px.line(df, x='Date', y='Users') +fig.show() + diff --git a/requirements.txt b/requirements.txt index f085cbb..5bd9931 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,9 +1,78 @@ -Click==7.0 -cx-Oracle==7.1.3 -Flask==1.0.2 -Flask-WTF==0.14.2 +appdirs==1.4.4 +attrs==19.3.0 +backcall==0.1.0 +bleach==3.1.5 +certifi==2020.4.5.1 +chardet==3.0.4 +click==7.1.2 +colorama==0.4.3 +cx-Oracle==7.3.0 +cycler==0.10.0 +decorator==4.4.2 +defusedxml==0.6.0 +distlib==0.3.0 +entrypoints==0.3 +filelock==3.0.12 +Flask==1.1.2 +gunicorn==20.0.4 +idna==2.9 +ipykernel==5.3.0 +ipython==7.14.0 +ipython-genutils==0.2.0 +ipywidgets==7.5.1 itsdangerous==1.1.0 -Jinja2==2.10.1 +jedi==0.17.0 +Jinja2==2.11.2 +joblib==0.15.1 +jsonschema==3.2.0 +jupyter==1.0.0 +jupyter-client==6.1.3 +jupyter-console==6.1.0 +jupyter-core==4.6.3 +kiwisolver==1.2.0 MarkupSafe==1.1.1 -Werkzeug==0.15.3 -WTForms==2.2.1 +matplotlib==3.2.1 +mistune==0.8.4 +nbconvert==5.6.1 +nbformat==5.0.6 +notebook==6.0.3 +numpy==1.18.4 +packaging==20.4 +pandas==1.0.4 +pandocfilters==1.4.2 +parso==0.7.0 +pickleshare==0.7.5 +pipenv==2018.11.26 +plotly==4.8.1 +prometheus-client==0.7.1 +prompt-toolkit==3.0.5 +Pygments==2.6.1 +pyparsing==2.4.7 +pyrsistent==0.16.0 +pyTelegramBotAPI==3.7.1 +python-dateutil==2.8.1 +pytz==2020.1 +pywin32==227 +pywinpty==0.5.7 +PyYAML==5.3.1 +pyzmq==19.0.1 +qtconsole==4.7.4 +QtPy==1.9.0 +requests==2.23.0 +retrying==1.3.3 +scipy==1.4.1 +Send2Trash==1.5.0 +six==1.15.0 +SQLAlchemy==1.3.17 +terminado==0.8.3 +testpath==0.4.4 +threadpoolctl==2.0.0 +tornado==6.0.4 +traitlets==4.3.3 +urllib3==1.25.9 +virtualenv==20.0.21 +virtualenv-clone==0.5.4 +wcwidth==0.1.9 +webencodings==0.5.1 +Werkzeug==1.0.1 +widgetsnbextension==3.5.1