def start_free_course(slug): """ The free Course start page. """ data = PageDetails().course_page_info(slug) if data is False: abort(404) course = Database().get_courses_data_from_db(slug) published_date = General().convert_timestamp_to_days( course["First_Created_TimeStamp"]) + course["Days_Till_Open"] if published_date > General().days_passed_till_now(): abort(404) try: identity = session["Data"]["Email"] except KeyError: identity = "" if slug in Database().get_users_access_data_from_db(identity): return redirect("/Course/{slug}".format(slug=slug)) if not (slug in Database().get_users_access_data_from_db(identity) or data[0]["Free"] is True or data[0]["Now_Price"] == 0): return redirect("/Course/{slug}/buy".format(slug=slug)) return render_template( "courses_and_days/start_course_card.html", course=data[0], days=data[1], intro=data[2], )
def form_handler(request): if request.form.get("slug") == "": return { "Result": False, "Message": "نام انگلیسی دوره را وارد کنید." } if request.form.get("day") == "": return {"Result": False, "Message": "روز دوره را وارد کنید."} try: int(request.form.get("day")) except ValueError: return {"Result": False, "Message": "روز دوره باید عدد باشد."} if Database().get_courses_data_from_db( request.form.get("slug")) is False: return { "Result": False, "Message": "همچین دوره ای وجود ندارد." } message = Database().delete_day_of_course_data_to_db( slug=request.form.get("slug"), day=request.form.get("day"), ) return message
def fail_page_course(slug): """ The Course Buy report fail page. """ data = PageDetails().course_page_info(slug) if data is False: abort(404) course = Database().get_courses_data_from_db(slug) published_date = General().convert_timestamp_to_days( course["First_Created_TimeStamp"]) + course["Days_Till_Open"] if published_date > General().days_passed_till_now(): abort(404) try: identity = session["Data"]["Email"] except KeyError: identity = "" if slug not in Database().get_users_access_data_from_db(identity): return redirect("/Course/{slug}".format(slug=slug)) try: code = (request.args['auth_code']) except KeyError: return redirect("/Course/{slug}".format(slug=slug)) return render_template("courses_and_days/fail_payment.html", course=data[0], days=data[1], intro=data[2], code=code)
def buy_course_redirect(slug): """ The Course redirect to zarinpall page. """ data = PageDetails().course_page_info(slug) if data is False: abort(404) course = Database().get_courses_data_from_db(slug) published_date = General().convert_timestamp_to_days( course["First_Created_TimeStamp"]) + course["Days_Till_Open"] if published_date > General().days_passed_till_now(): abort(404) try: identity = session["Data"]["Email"] except KeyError: return redirect("/LogIn") if slug in Database().get_users_access_data_from_db(identity): return redirect("/Course/{slug}".format(slug=slug)) client = Client(ZARINPAL_WEBSERVICE) result = client.service.PaymentRequest( MMERCHANT_ID, int(str(data[0]["Now_Price"]).replace(",", "")), description, 'email', "mobile", str(url_for('courses_and_days.buy_callback', _external=True))) if result.Status == 100: Database().add_payment_record_to_db(slug, data[0]["Now_Price"], identity, str(result.Authority)) return redirect('https://www.zarinpal.com/pg/StartPay/' + result.Authority) else: return 'Error'
def buy_callback(): """ The Course callback page from zarinpall page. """ client = Client(ZARINPAL_WEBSERVICE) payment_data = Database().get_payment_data(str(request.args['Authority'])) if request.args.get('Status') == 'OK': result = client.service.PaymentVerification( MMERCHANT_ID, request.args['Authority'], int(str(payment_data["Price"]).replace(',', ''))) if result.Status == 100 or result.Status == 101: Database().add_users_access_data_to_db(payment_data["Buyer"], payment_data["Slug"]) Database().change_payment_status_to_success_in_db( str(request.args['Authority'])) return redirect( "/Course/{slug}/buy/success?auth_code={code}".format( slug=payment_data["Slug"], code=str(request.args['Authority']))) else: Database().change_payment_status_to_fail_in_db( str(request.args['Authority'])) return redirect("/Course/{slug}/buy/fail?auth_code={code}".format( slug=payment_data["Slug"], code=str(request.args['Authority']))) else: Database().change_payment_status_to_fail_in_db( str(request.args['Authority'])) return redirect("/Course/{slug}/buy/fail?auth_code={code}".format( slug=payment_data["Slug"], code=str(request.args['Authority'])))
def form_handler(request): if request.form.get("slug") == "": return { "Result": False, "Message": "نام انگلیسی دوره را وارد کنید." } if request.form.get("day") == "": return {"Result": False, "Message": "روز دوره را وارد کنید."} if list(filter(None, request.form.getlist("quote"))) == []: return {"Result": False, "Message": "نقل قول ها را وارد کنید."} quotes = list(filter(None, request.form.getlist("quote"))) try: int(request.form.get("day")) except ValueError: return {"Result": False, "Message": "روز دوره باید عدد باشد."} if Database().get_courses_data_from_db( request.form.get("slug")) is False: return { "Result": False, "Message": "همچین دوره ای وجود ندارد." } message = Database().add_day_quotes_data_to_db( course_name_slug=request.form.get("slug"), day_num=request.form.get("day"), quotes=quotes, ) return message
def withdraw(): username = request.form.get("username") password = request.form.get("password") csrf_token = request.form.get("csrftoken") secret = request.cookies.get("secret") print(username, password, secret) if username != 'user1' or password != 'password' or not secret: return redirect(url_for('account')) if get_csrf_token(secret) != csrf_token: return redirect(url_for('account')) with Database() as db: db.execute("select amount from accounts where username = ?", (username, )) data = db.fetchone() if not data: return redirect(url_for('account')) if data[0] > 0: with Database() as db: db.execute("update accounts set amount = amount - 1 where username = ?", (username, )) return redirect(url_for('account'))
def form_course(request): if request.form.get("slug") == "": return {"Message": "نام انگلیسی دوره را وارد کنید."} slug = request.form.get("slug").replace(" ", "-") try: uploaded_file = request.files["cover"] except: return {"Message": "تصویر را آپلود کنید."} try: length_of_course = int(request.form.get("len")) except ValueError: return {"Color": "red", "Message": "طول دوره باید عدد باشد."} if (Database().get_courses_data_from_db(slug) != "" and uploaded_file.filename == ""): return {"Message": "تصویر را آپلود کنید."} result_pic = General().save_picture_of_course( slug, uploaded_file, length_of_course) if result_pic["Result"] is False: return result_pic if request.form.get("price-status") == "Free": price = "0" free = True else: price = request.form.get("price") free = False try: if request.form.get("soon") == "Soon": days_till_open = int(request.form.get("date_open")) else: days_till_open = 0 except ValueError: General().remove_file(result_pic["path"]) return { "Color": "red", "Message": "فاصله زمانی تا باز شدن باید عدد باشد." } try: int(price.replace(",", "")) except ValueError: General().remove_file(result_pic["path"]) return {"Color": "red", "Message": "قیمت دوره باید عدد باشد."} message = Database().add_course_data_to_db( name=request.form.get("name"), slug=slug, description=request.form.get("description"), intro=None, image_href=result_pic["href"], now_price=int(price.replace(",", "")), length_of_course=int(request.form.get("len")), robbin=request.form.get("robbin"), free=free, days_till_publish=days_till_open) if message is not True: General().remove_file(result_pic["path"]) return message
def form_handler(request): urls = request.form.getlist("animation_url") qualities = request.form.getlist("animation_quality") if request.form.get("slug") == "": return { "Result": False, "Message": "نام انگلیسی دوره را وارد کنید." } if request.form.get("day") == "": return {"Result": False, "Message": "روز دوره را وارد کنید."} if request.form.get("description") == "": return { "Result": False, "Message": "توضیحات ویدیو را وارد کنید." } for url in urls: if url == "": urls.remove(url) for quality in qualities: if quality == "": qualities.remove(quality) if urls == [] or qualities == []: return { "Result": False, "Message": "لینک و یا کیفیت ها را وارد کنید." } if not (len(urls) == len(qualities)): return { "Result": False, "Message": "همه فیلد های انیمیشن را وارد کنید.", } try: int(request.form.get("day")) except ValueError: return {"Result": False, "Message": "روز دوره باید عدد باشد."} if Database().get_courses_data_from_db( request.form.get("slug")) is False: return { "Result": False, "Message": "همچین دوره ای وجود ندارد." } message = Database().add_day_animation_data_to_db( course_name_slug=request.form.get("slug"), day_num=request.form.get("day"), description=request.form.get("description"), urls=urls, qualities=qualities, ) return message
def form_handler(request): creator = request.form.get("creator") name = request.form.get("podcast_name") cover = request.files.get("cover") url = request.form.get("podcast_url") if creator == "" or name == "": return { "Result": False, "Message": "اطلاعات پادکست را وارد کنید." } if request.form.get("slug") == "": return { "Result": False, "Message": "نام انگلیسی دوره را وارد کنید." } if request.form.get("day") == "": return {"Result": False, "Message": "روز دوره را وارد کنید."} if request.form.get("description") == "": return { "Result": False, "Message": "توضیحات پادکست را وارد کنید." } if url == "": return { "Result": False, "Message": "لینک پادکست را وارد کنید." } if cover.filename == "": return { "Result": False, "Message": "کاور پادکست را وارد کنید." } try: int(request.form.get("day")) except ValueError: return {"Result": False, "Message": "روز دوره باید عدد باشد."} if Database().get_courses_data_from_db( request.form.get("slug")) is False: return { "Result": False, "Message": "همچین دوره ای وجود ندارد." } message = Database().add_day_podcast_data_to_db( course_name_slug=request.form.get("slug"), day_num=request.form.get("day"), description=request.form.get("description"), url=url, cover=cover, creator=creator, name=name, ) return message
def __init__(self, username): mixer.init() self.username = username self.id = uuid.uuid1().time_low self.difficulty = 1 self.setup() self.MainView = MainView(self) self.muted = False self.create_sound() self.database = Database(self)
def blog_post(english_name): """ One post from Blog """ post = Database().get_blog_post_data_from_db(english_name) if post is False: abort(404) return render_template( "blog/blog_post.html", posts=Database().get_blog_posts_data_from_db(), postss=Database().get_blog_posts_data_from_db(), days_passed_till_now=General().days_passed_till_now(), post=post)
def launch(cls): workdays = TradingPeriod.get_workdays(begin='2016-12-31', end='2019-12-31') workdays_exchange_trading_period_by_ts = \ TradingPeriod.get_workdays_exchange_trading_period( _workdays=workdays, exchange_trading_period=EXCHANGE_TRADING_PERIOD) while True: if Utils.exit_flag: msg = 'Thread DataArrangeEngine say bye-bye' print msg logger.info(msg=msg) return try: awp_tick = db.r.lpop(app.config['data_stream_queue']) if awp_tick is None: time.sleep(1) continue awp_tick = json.loads(awp_tick) # 过滤交易量为 0 的假数据 if 'volume' in awp_tick and awp_tick['volume'] == 0: continue contract_code = pattern.match( awp_tick['instrument_id']).group() action_day = awp_tick['action_day'] update_time = awp_tick['update_time'] # 时间合法性校验 if not trading_time_filter( date_time=' '.join([action_day, update_time]), contract_code=contract_code, exchange_trading_period_by_ts= workdays_exchange_trading_period_by_ts['-'.join([ action_day[:4], action_day[4:6], action_day[6:] ])]): continue cls.data_arrange(awp_tick=awp_tick) except AttributeError as e: logger.error(traceback.format_exc()) time.sleep(1) if db.r is None: db.init_conn_redis() except Exception as e: logger.error(traceback.format_exc()) time.sleep(1)
def initialize_database(): """ Initializes database. :return: prints status of database to screen """ database = Database() if not os.path.isfile(database.database_filename): database.create_tables() print 'Database tables created successfully. Filename:', database.database_filename else: print 'Database already initialized. Filename:', database.database_filename
def setUp(self): """Creates test sqlite3 database and inserts test records.""" self.test_db = Database(self.test_db_filename) self.test_contacts = [ ("Test1a", "Test1b", "123456789", "*****@*****.**", "2017-12-11"), ("Test2a", "Test2b", "123456789", "*****@*****.**", "2017-12-12"), ("NotTo", "BeFound", "987654321", "*****@*****.**", "2017-12-13"), ] with sqlite3.connect(self.test_db_filename) as conn: c = conn.cursor() c.executemany("INSERT INTO Contacts VALUES (?, ?, ?, ?, ?)", self.test_contacts)
def launch(cls): logger.info(msg='Thread EventProcessor is launched.') while True: if Utils.exit_flag: msg = 'Thread EventProcessor say bye-bye' print msg logger.info(msg=msg) return try: report = db.r.lpop(app.config['upstream_queue']) if report is None: time.sleep(1) continue cls.message = json.loads(report) if cls.message['kind'] == EmitKind.log.value: cls.log_processor() elif cls.message['kind'] == EmitKind.guest_event.value: cls.guest_event_processor() elif cls.message['kind'] == EmitKind.host_event.value: cls.host_event_processor() elif cls.message['kind'] == EmitKind.response.value: cls.response_processor() elif cls.message[ 'kind'] == EmitKind.guest_collection_performance.value: cls.guest_collection_performance_processor() elif cls.message[ 'kind'] == EmitKind.host_collection_performance.value: cls.host_collection_performance_processor() else: pass except AttributeError as e: logger.error(traceback.format_exc()) time.sleep(1) if db.r is None: db.init_conn_redis() except Exception as e: logger.error(traceback.format_exc()) time.sleep(1)
class CreateTournamentController: """ This controller creates a tournament and allows to add 8 players. The tournament and the 8 players are savend in the database in their own table. """ def __init__(self): self.tournament_view = TournamentView() self.player_view = PlayerView() self.db = Database() self.players = self.db.load_player_data() def __call__(self): if len(self.db.all_tournaments_in_progress()) > 0: self.tournament_view.display_error_tournament_active() else: tournament_infos = self.tournament_view.get_info() tournament = Tournament(name=tournament_infos[0], location=tournament_infos[1], number_of_turns=int(tournament_infos[2]), description=tournament_infos[3], time_control=tournament_infos[4]) tournament.save_in_db() n = 1 while n < 9: self.add_a_player(tournament=tournament) self.tournament_view.incremented_player_number(n) n += 1 return HomeMenuController() def add_a_player(self, tournament: Tournament): """ Create a player instance and save data in the table "players" from the database """ player_infos = self.player_view.check_if_player_exists() player_first_name = player_infos[0] player_last_name = player_infos[1] if (player_first_name, player_last_name) not in [ (i.first_name, i.last_name) for i in self.players ]: more_infos = self.player_view.ask_more_infos() Player(first_name=player_first_name, last_name=player_last_name, birth=more_infos[0], gender=more_infos[1]).save_in_db() for player in self.db.load_player_data(): if player.first_name == player_first_name and player.last_name == player_last_name: player = player.get_document_from_instance() tournament.add_player_in_tournament(player)
def form_handler(request): if request.form.get("slug") == "": return { "Result": False, "Message": "نام انگلیسی دوره را وارد کنید." } if request.form.get("day") == "": return {"Result": False, "Message": "روز دوره را وارد کنید."} try: int(request.form.get("day")) except ValueError: return {"Result": False, "Message": "روز دوره باید عدد باشد."} if Database().get_courses_data_from_db( request.form.get("slug")) is False: return { "Result": False, "Message": "همچین دوره ای وجود ندارد." } remove_ones = [] day_parts = [ "Name", "Cover", "Description", "Text", "To_Do", "Quotes", "Musics", "Musics_Description", "Ted_Video", "Ted_Video_Description", "Animation_Link", "Animation_Description", "Movie_Links", "Movie_Text", "Movie_Cover", "Podcast", "Podcast_Description", ] for part in day_parts: if (part) == request.form.get(part): remove_ones.append(part) message = Database().delete_parts_of_day_of_course_data_in_db( slug=request.form.get("slug"), day_of_course=request.form.get("day"), remove_parts_names=remove_ones, ) return message
def db_integration(): peps = PEPScrap("https://www.python.org/dev/peps/").data_pep() db = Database() if os.path.abspath(os.getcwd()).endswith("app") else Database("app") db.create_db() db_session = DBSession(db.engine) new_peps = [] for pep in peps: if db_session.add_pep(pep): new_peps.append(pep) users = db_session.get_users() mail = Mail("*****@*****.**", "acapep2021") mail.send_info(users, new_peps)
def sub_course(slug, day): """ The one sub Course page. """ # Day is a number or not try: day = int(day) except ValueError: abort(404) course = Database().get_courses_data_from_db(slug) published_date = General().convert_timestamp_to_days( course["First_Created_TimeStamp"]) + course["Days_Till_Open"] if published_date > General().days_passed_till_now(): abort(404) try: identity = session["Data"]["Email"] except KeyError: identity = "" # Get needed Data course_data = Database().get_courses_data_from_db(slug=slug) day_data = Database().get_one_day_data_of_courses_data_from_db(slug, day) # Check Length Day if int(day) > int(course_data["Length"]): return redirect("/Course/{}".format(slug)) # Check if data is FALSE or not if course_data is False or day_data is False: abort(404) # Some days and courses in database might not have "Free" key, so we add them. if "Free" not in day_data: day_data["Free"] = False if "Free" not in course_data: course_data["Free"] = False # Check if day or course is not free and if we do not have access user_accesses = Database().get_users_access_data_from_db(identity) if (course_data["Free"] is not True and slug not in user_accesses and day_data["Free"] is False): return redirect("/Course/{}/info".format(slug)) if slug in user_accesses and (user_accesses[slug] - 1 + day - General().days_passed_till_now()) > 0: return redirect("/Course/{}".format(slug)) return render_template( "courses_and_days/day.html", course=PageDetails(session).course_page_info(slug)[0], day=PageDetails(session).sub_course_page_info_html(slug, day), )
def create_database(name, realuser): # let's create database in the real world connection = engine.connect() prepare_statement = text((stmt_create_db % name)) create_result = connection.execute(prepare_statement) connection.close() database = Database() database.name = name database.realuser = realuser db_session.add(database) db_session.commit()
def form_handler(request): text = request.form.get("text") day = request.form.get("day") slug = request.form.get("slug") if slug == "": return { "Result": False, "Message": "نام انگلیسی دوره را وارد کنید." } if request.form.get("day") == "": return {"Result": False, "Message": "روز دوره را وارد کنید."} if text == "": return {"Result": False, "Message": "متن اصلی را وارد کنید."} try: int(day) except ValueError: return {"Result": False, "Message": "روز دوره باید عدد باشد."} if Database().get_courses_data_from_db(slug) is False: return { "Result": False, "Message": "همچین دوره ای وجود ندارد." } links_images = re.findall("src=[\"\'](.*?)[\"\']", text) if General().check_existence_of_a_file( "static/assets/courses/{slug}/days/{day}".format( slug=slug, day=day)) is False: General().setup_course_folder(slug) for link in links_images: file_path = General().href_to_path(link) file_name = (file_path.split("/"))[-1] new_file_path = "static/assets/courses/{slug}/days/{day_number}/{file_name}".format( slug=slug, day_number=day, file_name=file_name) new_file_href = "/static//assets/courses/{slug}/days/{day_number}/{file_name}".format( slug=slug, day_number=day, file_name=file_name) General().move_file_path(file_path, new_file_path) text = text.replace(link, new_file_href) message = Database().add_day_text_data_to_db( course_name_slug=slug, day_num=day, text=text, ) return message
def form_handler(request): name = request.form.get("tool_name") remove_ones = [] tool_names = [] for tool_name in Database().get_all_tools_data_db(): tool_names.append(tool_name["Slug"]) for part in tool_names: if part == request.form.get(part): remove_ones.append(part) for tool_slug in remove_ones: Database().delete_tool_data_from_db(tool_slug) message = True return message
def form_handler(request): name = request.form.get("music_name") remove_ones = [] music_names = [] for music_name in Database().get_all_musics_data_from_db(): music_names.append(music_name["Music_Name"]) for part in music_names: if (part) == request.form.get(part): remove_ones.append(part) for music_name in remove_ones: Database().delete_music_data_from_db(music_name) message = True return message
def musics_index(): """ The Music page """ posts_per_page = 10 page = request.args.get("page") posts = Database().get_all_musics_data_from_db() last_page = len(posts) // posts_per_page if len(posts) - last_page * posts_per_page > 0: last_page += 1 if page is None: page = 1 else: try: page = int(page) except ValueError: page = 1 if page < 1: return redirect("?page=1") limited_posts = (posts[(page - 1) * posts_per_page:page * posts_per_page]) if limited_posts == [] and page != 1: return redirect("?page={}".format(last_page)) return render_template("music/music_posts.html", posts=limited_posts, now_page=page, last_page=last_page, pagination=General().pagination_designer( page, last_page))
def tools_index(): """ The Tools page """ posts_per_page = 9 page = request.args.get("page") posts = Database().get_all_tools_data_db() last_page = len(posts) // posts_per_page if len(posts) - last_page * posts_per_page > 0: last_page += 1 if page is None: page = 1 else: try: page = int(page) except ValueError: page = 1 if page < 1: return redirect("?page=1") limited_posts = (posts[(page - 1) * posts_per_page:page * posts_per_page]) if limited_posts == [] and page != 1: return redirect("?page={}".format(last_page)) return render_template( "tools/tools_index.html", posts=limited_posts, now_page=page, last_page=last_page, pagination=General().pagination_designer(page, last_page), days_till_now=General().days_passed_till_now(), )
def update_db(): if request.method == 'GET': return ''' <!doctype html> <title>Get database date</title> <h1>Get database date</h1> <form action="" method=post> <p><input type=text name=message> <input type=submit value=Send> </form> ''' elif request.method == 'POST': date_string = request.form['message'] # if sent date < modified date if Database.need_update(date_string): conn = sqlite3.connect('updated.db') c = conn.cursor() c.execute("DELETE FROM user") for user in User.query.all(): username = user.username password = user.password c.execute("INSERT INTO user VALUES(NULL, '%s', '%s')" % (username, password)) conn.commit() conn.close() with open('updated.db', 'r') as f: g = f.read() return base64.b64encode(g) else: return 'OK' """
def form_handler(request): cover = request.files.get("cover") music = request.files.get("music") creator = request.form.get("creator") name = request.form.get("music_name") if music.filename == "": return {"Result": False, "Message": "موزیک را اپلود کنید."} if cover.filename == "": return {"Result": False, "Message": "کاور را اپلود کنید."} if name == "" or creator == "": return { "Result": False, "Message": "اطلاعات موزیک را وارد کنید." } message = Database().add_music_data_to_db( cover=cover, music=music, creator=creator, name=name, ) return message
def add_course_info_admin(): """ The Add Course information Page as an admin. """ if request.method == "POST": message = Database().add_course_info_to_db( slug=request.form.get("slug"), introduction=request.form.get("intro"), speciality=request.form.get("speciality"), importance=request.form.get("importance"), why=request.form.get("why"), length=request.form.get("length"), price=request.form.get("price"), last_words=request.form.get("last_word"), ) if message is True: message = {"Color": "green", "Result": "با موفقیت اضافه شد."} else: message["Result"] = message["Message"] message["Color"] = "red" flash(message) return redirect(url_for("admin_add.add_course_info_admin")) return render_template( "admin/admin_add_course_info.html", Courses=PageDetails(). get_all_courses_info_categorized_by_info_existence(), )
def get_openmrs_contacts(self): """ Get contacts from OPENMRS """ mrs_database = Database().get_openmrs_db() connection = vm.get_db_connector(mrs_database.hostname, mrs_database.username, mrs_database.password, mrs_database.database) last_checked = ConnectorUtils().get_last_checked(self.type_id) if self.type_id == ENROLLMENT_TYPE_ID: last_checked = ConnectorUtils().get_last_checked(self.type_id) contacts = vm.get_clients_enrollment_contacts( connection, last_checked) elif self.type_id == KICKOFF_TYPE_ID: last_checked = ConnectorUtils().get_last_checked(self.type_id) contacts = vm.get_kickoff_client_contacts(connection, last_checked) elif self.type_id == BIRTHDAY_TYPE_ID: contacts = vm.get_birthday_contacts(connection) elif self.type_id == APPOINTMENT_REMINDER_TYPE_ID: contacts = vm.get_appointment_booking_contacts( connection, last_checked) else: last_checked = ConnectorUtils().get_last_checked(self.type_id) contacts = vm.get_clients_enrollment_contacts( connection, last_checked) return contacts
def remove_post_blog_admin(slug_post): """ The remove a Post for blog Page as an admin. """ post = Database().get_blog_post_data_from_db(slug_post) if post is False: abort(404) if request.method == "POST": def form_handler(request): if request.form.get("confirmation") == "True": message = Database().delete_post_blog_data_from_db(slug_post) else: message = {"Result": False, "Message": "حذف تایید نشده است."} General().remove_file_to_trash( "static/assets/images/blog/{slug}/".format(slug=slug_post)) return message message = form_handler(request) if message is True: message = {"Color": "green", "Result": "با موفقیت حذف شد."} else: if message["Result"] is False: message["Color"] = "red" else: message["Color"] = "green" message["Result"] = message["Message"] flash(message) return redirect(url_for("admin_edit.post_blog_options_admin")) return render_template("admin/admin_remove_post.html", post=post)
def json2schema(schema_json, commit = True, destdb = None): """ Creates Database, Table, and Column objects as needed to satisfy the incoming schema. If the table is already present, assume we are updating: delete all columns and recreate from the schema. Unless commit is false, call the required sql to create the incoming tables in the destination database. """ schema = json.loads(schema_json) for dbname, table_schema in schema.iteritems(): if destdb: dbname = destdb try: db = Database.objects.get(name=dbname) except Database.DoesNotExist: db = Database(name=dbname) db.save() for tablename, column_schema in table_schema.iteritems(): try: table = Table.objects.get(db=db, name=tablename) for column in Column.objects.filter(table=table): column.delete() except Table.DoesNotExist: table = Table(db=db, name=tablename) table.save() for columnname, columntype in column_schema.iteritems(): column = Column(table=table, name=columnname, type=columntype) column.save() if commit: model = ModelGenerator.getModel(dbname, tablename) cursor = connections[dbname].cursor() for sql in ModelGenerator.getSQL(model): cursor.execute(sql) return None
def login(): if request.method == "POST" and "username" in request.form: username = request.form["username"] password = request.form["password"] error_code = Database.connect(username, password) if error_code: flash("You typed in an invalid username/password") else: if username in USER_NAMES: remember = request.form.get("remember", "no") == "yes" if login_user(USER_NAMES[username], remember=remember): flash("Logged in!") return redirect(request.args.get("next") or url_for("index")) else: flash("Sorry, but you could not log in.") else: flash("You are not allowed to use this interface. Contact sgd-programmers to add your name to the list.") return render_template("login.html")
from models import Database cursor = Database.execute('show tables')
from models import Database Database.change('db2') # change to `db2`
import sendgrid import util, configparser, getopt, subprocess, sys, time, psutil #from models import ProcessTimeSeries from models import Database start_time = time.time() # initial setup config = util.readConfig() logger = util.getLogger(config) sg = util.getSendGrid(config) db = Database(config) # parse arguments try: opts, args = getopt.getopt(sys.argv[1:], "hvrt", ["--restarts"]) except getopt.GetoptError: print ("Not enough options") sys.exit(2) for opt, arg in opts: if opt == '-h': util.printhelp() sys.exit(0) elif opt in ("-r", "--restarts"): util.printrestarts(config) sys.exit(0) elif opt in ("-t", "--time"): util.printtimeseries(config) sys.exit(0) elif opt == "-v":