def db_start(): app.app_context().push() db.create_all() config = configparser.ConfigParser() config.read('config.ini') engine = create_engine(config['DB']['SQLALCHEMY_DATABASE_URI'], convert_unicode=True) if not database_exists(engine.url): create_database(engine.url) db.create_all() db.session.commit()
def init_admin(): user = User() user.username = "******" user.password = generate_password_hash('admin', method='sha256') user.email = '*****@*****.**' user.admin = True user.poweruser = True try: sa.orm.configure_mappers() app.app_context().push() db.session.add(user) db.session.commit() except IntegrityError as e: print('W bazie istnieje już użytkownik o nazwie: ' + user.username)
def session(app, db, request): """ Returns function-scoped session. """ with app.app_context(): conn = _db.engine.connect() txn = conn.begin() options = dict(bind=conn, binds={}) sess = _db.create_scoped_session(options=options) # establish a SAVEPOINT just before beginning the test # (http://docs.sqlalchemy.org/en/latest/orm/session_transaction.html#using-savepoint) sess.begin_nested() @event.listens_for(sess(), "after_transaction_end") def restart_savepoint(sess2, trans): # Detecting whether this is indeed the nested transaction of the test if trans.nested and not trans._parent.nested: # The test should have normally called session.commit(), # but to be safe we explicitly expire the session sess2.expire_all() sess.begin_nested() _db.session = sess yield sess # Cleanup sess.remove() # This instruction rollsback any commit that were executed in the tests. txn.rollback() conn.close()
def send_mail(sender, recipients, theme, body, html): message_to_send = Message(theme, sender=sender, recipients=[recipients]) message_to_send.body = body message_to_send.html = html with app.app_context(): mail.send(message_to_send)
def price_alert(listing): # get trackers trackers = db.session.query(Tracker).all() for tracker in trackers: # if listing is tracked by tracker tracked_words = set(tracker.search.lower().split(" ")) if set(listing.name.lower().split(" ")).intersection( tracked_words) == tracked_words: print("this is tracked:", listing.name) # if listing price triggers price alert if listing.price <= tracker.alert_price or listing.price <= tracker.ave_price * tracker.alert_percentage: # generate and send price alert email with app.app_context(): html_template = render_template( "price_alert_email_template.html", listing=listing, tracker=tracker) to_email = str(tracker.user_email) send_alert(to_email, html_template) print("Data alert: ", listing.link) # update tracker ave_price and tracked items tracker.tracked_items = int(tracker.tracked_items) + 1 tracker.ave_price = (tracker.ave_price + listing.price) / tracker.tracked_items db.session.commit()
def db(app, request): """ Returns session-wide initialised database. """ _db.init_app(app) with app.app_context(): _db.drop_all() _db.create_all()
def add_supp(): app.app_context().push() db.create_all() """ suppliers_id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), nullable=False) nip = db.Column(db.String(30), nullable=False) adress = db.Column(db.String(80), nullable=False) discount = db.Column(db.Float, default=0) """ supplier1 = Suppliers(name='Engine Company 2', nip='35223425525', address="Engine town", discount=10.15) sa.orm.configure_mappers() app.app_context().push() db.create_all() db.session.add(supplier1) db.session.commit()
def sendmail(notification): message = Message( subject=_('You have a notification from Better Translator'), body=notification.payload, sender=(_('app-title'), '*****@*****.**'), recipients=[notification.user.email] ) with app.app_context(): mail.send(message) db.session.delete(notification)
def db_start(): db.init_app(app.app_context()) config = configparser.ConfigParser() config.read('config.ini') # engine = create_engine('postgresql://*****:*****@localhost/stock_manager', convert_unicode=True) engine = create_engine(config['DB']['SQLALCHEMY_DATABASE_URI'], convert_unicode=True) if not database_exists(engine.url): create_database(engine.url) db.create_all() db.session.commit()
def generate_notification(): user_id = request.json['user_id'] with app.app_context(): msg = Message( subject="[Urgent] Get yourself tested for COVID-19 and quarantine.", sender=app.config.get("MAIL_USERNAME"), recipients=[user_id], # replace with your email for testing body= "Hello, \r\nGreetings for the day. \r\nYou were in proximity of a person in the last 14 days who is currently infected from COVID-19. We highly recommend you to get yourself tested as soon as possible and quarantine yourself to prevent the spread of virus.\r\nStay Home, Stay Safe. \r\nBest Regards,\r\nPandemic Response Team " ) mail.send(msg) return {"message": "success"}, 200
def say_hello(): with app.app_context(): app.logger.debug("adding to the log") test_dict["value"] += 33 return 'hello world ' + str(test_dict["value"])
for opportunity in opportunities: html += f"<a href='{baseurl}/opportunities/{opportunity.opportunityID}'>{opportunity.title}</a><br>" html += "<br>--<br>Caerus</body></html>" return html # https://support.google.com/mail/answer/7126229?p=BadCredentials&visit_id=637267656946578056-6078978&rd=2#cantsignin # https://www.digitalocean.com/community/tutorials/how-to-use-cron-to-automate-tasks-ubuntu-1804 # https://realpython.com/python-send-email/ if __name__ == "__main__": db.init_app(app) with app.app_context(): db.create_all() info = getPreferredOpportunitiesForAllUsers() notifier = Notifier(user, pwd) for email in info.keys(): prefs = getAllPreferences(info[email]['id']) opps = info[email]['opportunities'] if len(opps) > 0: html = constructBody(opps, prefs) time = datetime.datetime.now() notifier.sendmail( [email], f"Caerus Weekly Update -- {time.date().isoformat()}", html) print( f"Notification email sent to {email} -- {time.isoformat()}"
@babel.localeselector def get_locale(): return 'ko' def sendmail(notification): message = Message( subject=_('You have a notification from Better Translator'), body=notification.payload, sender=(_('app-title'), '*****@*****.**'), recipients=[notification.user.email] ) with app.app_context(): mail.send(message) db.session.delete(notification) def main(): for notification in NotificationQueue.query.all(): sendmail(notification) db.session.commit() if __name__ == '__main__': #main() with app.app_context(): print _('app-title')
def send_async_email(app, msg): with app.app_context(): mail.send(msg)
from invoices.models import Products def search_engine(query): product_list = {"Products":[]} if query: search_results = Products.query.order_by(Products.products_id) search_results = search(search_results, query) else: search_results = Products.query.order_by(Products.products_id) for r in search_results: product_name = str(r) product_list["Products"].append({"name": product_name[1:-1], "columns": [ r.products_id, r.name, r.group, r.stock_quantity, r.price, r.supplier_id ]}) return product_list if __name__ == '__main__': from __init__ import app app.app_context().push() db.create_all() search_engine(query)
import csv import datetime from __init__ import app from config import Config from models import * with app.app_context(), open('meetup_events.csv', 'r') as data: events_csv = csv.reader(data) events = list(events_csv) for row in events[1:]: loc = db.session.query(Location).filter( Location.code == row[6]).first() date = datetime.datetime.strptime(row[2] + row[3], '%d.%m.%Y%H:%M') event = Event( title=row[0], description=row[1], datetime=date, category=row[4], type=row[5], location=loc, address=row[7], seats=row[8], ) db.session.add(event) db.session.commit()