def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)
    # all_posts = Post.query.all()
    # print(all_posts)
    return app
Exemplo n.º 2
0
def create_app():

    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)

    @app.route('/')  # main page
    def index():
        title = "Tiger"

    @app.route('/input_roast')
    def input_roast():
        title = "Input Roasting"
        input_form = Input_roast()
        return render_template('input.html', page_title=title, form=input_form)

    @app.route('/input_file')
    def input_file():
        title = "Input roasting file"
        input_form = Input_File()
        return render_template('input_file.html',
                               page_title=title,
                               form=input_form)

    return app
Exemplo n.º 3
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'user.login'
    app.register_blueprint(user_blueprint)

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)

    @app.route('/')
    def index():
        page_title = 'First page'
        text = 'it is working'
        return render_template('index.html', page_title=page_title, text=text)

    @app.route('/admin')
    @login_required
    def admin_index():
        if current_user.is_admin:
            return 'Hi admin'
        else:
            return 'You are not admin'

    return app
Exemplo n.º 4
0
def create_app():
    app = Flask(__name__)
    csrf = CSRFProtect(app)
    csrf.init_app(app)
    app.config.from_pyfile('config.py')
    db.init_app(app)
    app.config['SECRET_KEY'] = SECRET_KEY

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'login'

    app.register_blueprint(user_blueprint)
    app.register_blueprint(picture_blueprint)
    app.register_blueprint(comment_blueprint)

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)

    @app.route('/')
    def index():
        return redirect(url_for('picture.pictures'))

    if __name__ == '__main__':
        app.run(debug=True)

    return app
Exemplo n.º 5
0
def create_app(config_name=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    app.config.from_mapping(
        DATABASE=os.path.join(app.instance_path, 'webapp.sqlite'))

    if config_name is None:
        # load the instance config, if it exists, when not testing
        app.config.from_object('webapp.config.ProductionConfig')
    else:
        # load the test config if passed in
        app.config.from_mapping(config_name)

    # initiate the module
    db.init_app(app)

    # load blueprints
    for blueprint in blueprints:
        app.register_blueprint(import_string(blueprint))

    return app


# if you use uWSGI to run the app, uncomment line below
# app = create_app()
Exemplo n.º 6
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile("config.py")
    db.init_app(app)

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'login'

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)

    @app.route("/")
    def index():
        title = "Новости Python"
        weather = weather_by_city(app.config["WEATHER_DEFAULT_CITY"])
        news_list = News.query.order_by(News.published.desc()).all()
        return render_template("index.html",
                               page_title=title,
                               weather=weather,
                               news_list=news_list)

    @app.route("/login")
    def login():
        if current_user.is_authenticated:
            return redirect(url_for('index'))
        title = "Авторизация"
        login_form = LoginForm()
        return render_template('login.html', page_title=title, form=login_form)

    @app.route("/process-login", methods=['POST'])
    def process_login():
        form = LoginForm()
        if form.validate_on_submit():
            user = User.query.filter(
                User.username == form.username.data).first()
            if user and user.check_password(form.password.data):
                login_user(user)
                flash('Вы вошли на сайт')
                return redirect(url_for('index'))

        flash('Неправильные имя или пароль')
        return redirect(url_for('login'))

    @app.route("/logout")
    def logout():
        logout_user()
        flash('Вы успешно разлогинилсь')
        return redirect(url_for('index'))

    @app.route("/admin")
    @login_required
    def admin_index():
        if current_user.is_admin:
            return "Привет админ!"
        else:
            return "Ты не админ!"

    return app
Exemplo n.º 7
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)
    jwt = JWTManager(app)
    CORS(app)
    return app
Exemplo n.º 8
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'login'

    @login_manager.user_loader
    def load_user(user_id):
        User.query.get(user_id)

    @app.route('/')
    def index():
        title = 'Новости Python'
        weather = weather_by_city(app.config['WEATHER_DEFAULT_CITY'])
        news_list = News.query.order_by(News.published.desc()).all()
        return render_template(
            'index.html',
            page_title=title,
            weather=weather,
            news_list=news_list)

    @app.route('/login')
    def login():
        if current_user.is_authenticated:
            return redirect(url_for('/index'))
        title = 'Authorization'
        login_form = LoginForm()
        return render_template('login.html', page_title=title, form=login_form)

    @app.route('/process-login', methods=['POST'])
    def process_login():
        form = LoginForm()
        if form.validate_on_submit():
            user = User.query.filter_by(username=form.username.data).first()
            if user and user.check_password(form.password.data):
                login_user(user)
                flash('Welcome')
                return redirect(url_for('index'))
        flash('Incorrect login or pass')
        return redirect(url_for('login'))

    @app.route('/logout')
    def logout():
        logout_user()
        flash("You're successfully logout")
        return redirect(url_for('index'))

    @app.route('/admin')
    @login_required
    def admin_index():
        return('Hello admin!')

    return app
Exemplo n.º 9
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)

    @app.route('/')
    def index():
        title = 'Список дел от Милены'
        tasks_milena = Tasks.query.with_entities(Tasks.task).all()
        return render_template("index.html", page_title=title, tasks_milena_list=tasks_milena)

    return app
Exemplo n.º 10
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)

    @ app.route("/")
    def index():
        title = "News & Weather"
        weather = weather_by_city(app.config['WEATHER_DEFAULT_CITY'])
        news_list = News.query.order_by(News.published.desc()).all()
        return render_template('index.html', page_title=title, weather=weather, news_list=news_list)

    return app
Exemplo n.º 11
0
def create_app():
    app = Flask(__name__)                # создаю Flask-приложение
    app.config.from_pyfile('config.py')  # указываю, откуда брать константы
    db.init_app(app)                     # инициализируем БД ПОСЛЕ config.py, т к в config.py лежит url
    @app.route('/')
    def index():
        title = 'Новости Python'        # переменная, которую мы вставляем в шаблон
        weather = weather_by_city(app.config['WEATHER_DEFAULT_CITY'])   # ('Moscow,Russia') - более ранний вариант
        # указания на город, до config.py Вытаскиваем константу "город" так же, как значение ключа словаря
        # news_list = get_python_news()  # вызываем функцию из парсера новостей (раняя редакция)
        news_list = News.query.order_by(News.published.desc()).all() # делаю Выборку Всех новостей -> располагаю По Порядку (от Свежей к старой)
        return render_template('index.html', page_title=title, weather=weather, news_list=news_list)
        # news_list - шаблон новостей для функции. В render_template передаем название файла
        # с шаблоном в кавычках + другие аргументы
    return app  # функция create_app возвращает Flask application
Exemplo n.º 12
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)

    @app.route('/')
    def index():
        title = 'Прогноз погоды и парсинг сайта'
        weather = weather_by_city(app.config['WEATHER_DEFAULT_CITY'])
        news_list = get_bdva_news()
        return render_template('index.html',
                               page_title=title,
                               weather=weather,
                               news_list=news_list)

    return app
Exemplo n.º 13
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)

    @app.route('/')
    def index():
        title = "Weather Forecast"
        weather = weather_by_city(app.config['WEATHER_DEFAULT_CITY'])
        news_list = get_weather_news()
        return render_template("index.html",
                               page_title=title,
                               weather=weather,
                               news_list=news_list)

    return app
Exemplo n.º 14
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)
    app.register_blueprint(user_blueprint)
    app.register_blueprint(event_blueprint)

    @app.route('/')
    def index():
        title = 'Главная страница'
        hello_text = 'Hello, world!'
        return render_template('index.html',
                               title=title,
                               hello_text=hello_text)

    return app
Exemplo n.º 15
0
def create_app():
    app = Flask(__name__)  # __name__ - имя текущего файла
    app.config.from_pyfile('config.py')
    db.init_app(app)

    @app.route('/')  # декоратор
    def index():
        title = 'Новости Python'
        weather = weather_by_city(app.config['WEATHER_DEFAULT_CITY'])
        news_list = News.query.order_by(News.published.desc()).all()
        return render_template('index.html',
                               page_title=title,
                               weather=weather,
                               news_list=news_list)

    return app
Exemplo n.º 16
0
def create_app():
    app = Flask(__name__)
    app.config['GOOGLEMAPS_KEY'] = config.GOOGLEMAPS_KEY
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SQLALCHEMY_DATABASE_URI'] = config.SQLALCHEMY_DATABASE_URI
    db.init_app(app)

    GoogleMaps(app)

    @app.route("/")
    def index():

        engine = create_engine(config.SQLALCHEMY_DATABASE_URI_LOCAL)
        connection = engine.connect()

        mymap = Map(
            identifier="view-side",
            lat=27.4419,
            lng=-112.1419,
        )

        markers = []
        rows = connection.execute(
            "SELECT latitude,longitude,callsign,datetime \
            FROM (SELECT   t.*, MAX(datetime) OVER (partition BY callsign) maxdatetime \
            FROM PUBLIC.trace AS t) AS tt \
            WHERE tt.datetime=tt.maxdatetime \
            ORDER BY callsign").fetchall()

        for row in rows:
            markers.append({
                'icon': 'http://maps.google.com/mapfiles/ms/icons/plane.png',
                'lat': row[0],
                'lng': row[1],
                'infobox': f"<b>{row[2]}</b>"
            })

        sndmap = Map(identifier="sndmap",
                     lat=55.9000,
                     lng=37.7800,
                     markers=markers,
                     zoom=3,
                     style="height:720px;width:1100px;margin:0;")

        return render_template('index.html', mymap=mymap, sndmap=sndmap)

    return app
Exemplo n.º 17
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)

    @app.route('/', methods=['GET', 'POST'])
    def index():
        forecast_form = GetDateForms()
        title = "WeatherStatistics"
        max_now = max(data_now)
        min_now = min(data_now)
        weather_text = weather_by_city(app.config["WEATHER_DEFAULT_CITY"])
        if int(weather_text['temp_C']) > 0:
            weather_nows = f'+{weather_text["temp_C"]}'
        if int(weather_text['temp_C']) <= -30:
            weather_nows_text = f'На моей мега-современной метеостанции термометр лопнул от холода. Сиди дома у печки!'
        elif int(weather_text['temp_C']) <= -15:
            weather_nows_text = f'Капитан подштанник! Сегодня ваш день!'
        elif int(weather_text['temp_C']) <= -1:
            weather_nows_text = f'Вот сейчас тебе самое время просить погодное убежище в Испании!'
        elif int(weather_text['temp_C']) <= 8:
            weather_nows_text = f'Ну, такое себе погода… Но на пробежку выйти тем не менее можно… Но в калошах.'
        elif int(weather_text['temp_C']) <= 19:
            weather_nows_text = f'Радость-то какая! Уже можно гулять в расстёгнутом пуховике (как тогда, в июне 2017го).'
        elif int(weather_text['temp_C']) <= 40:
            weather_nows_text = f'Вроде потеплело :) Но это не точно:( Рекомендую шубу и валенки далеко не убирать.'
        #показать все данные из таблицы
        #weather_table = weatherquery.all()

        date = request.args.get('date')
        month = request.args.get('month')
        average_temp = average(date, month)

        #reminder = cat_reminder()

        return render_template('index.html',
                               average_temp=average_temp,
                               page_title=title,
                               weather_nows=weather_nows,
                               weather_nows_text=weather_nows_text,
                               max_now=max_now,
                               min_now=min_now,
                               form=forecast_form)

    return app
Exemplo n.º 18
0
def create_app():

    app = Flask(__name__)
    app.config.from_pyfile('config.py')  # добавляем файл конфиг
    db.init_app(app)

    @app.route('/')
    def index():
        title = 'Новости Python'
        weather = weather_by_city(app.config['WEATHER_DEFAULT_CITY'])
        news_list = News.query.order_by(News.published.desc()).all(
        )  # order_by(News.published.desc() делаем вывод новостей из базы данных по дате, начиная с самых новых published.desc()
        return render_template('index.html',
                               page_title=title,
                               weather=weather,
                               news_list=news_list)

    return app
Exemplo n.º 19
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('settings.py')
    db.init_app(app)
    migrate = Migrate(app, db)

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'user.login'
    app.register_blueprint(admin_blueprint)
    app.register_blueprint(news_blueprint)
    app.register_blueprint(user_blueprint)

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)

    return app
Exemplo n.º 20
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)

    @app.route('/<int:page_num>')
    @app.route('/home/<int:page_num>')
    def home(page_num):
        title = 'Новости'
        news_list = News.query.paginate(page=page_num,
                                        per_page=10,
                                        error_out=True)

        return render_template('index.html',
                               page_title=title,
                               news_list=news_list)

    return app
Exemplo n.º 21
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile("config.py")
    db.init_app(app)
    migrate = Migrate(app, db)

    @app.route('/')
    def index():
        locale.setlocale(locale.LC_ALL, "russian")
        dt_now.strftime('%A %d %B %Y')
        day = dt_now.strftime('%d.%m.%y')
        title = f"Сегодня {dt_now.strftime('%A %d %B %Y')} года"
        input_form = InputForm()
        return render_template('input.html',
                               page_title=title,
                               day=day,
                               form=input_form)

    @app.route('/save-news', methods=['POST'])
    def save_news():
        form = InputForm()
        if form.validate_on_submit():
            date = form.today.data
            date = datetime.strptime(date, '%d.%m.%y').date()
            #            news = f'{form.news.data}\n'
            news = {form.news.data}

            new_day = Everyday(day_data=date, day_news=news)

            db.session.add(new_day)
            db.session.commit()

            return redirect(url_for('day_process'))

    @app.route('/day_process', methods=['GET'])
    def day_process():
        my_day = Everyday.query.all()[-1]
        print(my_day.day_data)
        input_form = InputForm()
        return render_template('output.html', my_day=my_day, form=input_form)

    return app
Exemplo n.º 22
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile("config.py")
    db.init_app(app)

    @app.route(
        '/')  # когда пользователь вводит адрес "/", вызывается функция index
    def index():
        title = "Новости Python"
        weather = weather_by_city(app.config["WEATHER_DEFAULT_CITY"])
        news_list = News.query.order_by(News.published.desc()).all()
        return render_template('index.html',
                               page_title=title,
                               weather=weather,
                               news_list=news_list)

    return app


#Запуск сервера в командной строке:
#set FLASK_APP=webapp && set FLASK_ENV=development && set FLASK_DEBUG=1 && flask run
Exemplo n.º 23
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)

    @app.route("/")
    def index():
        title = 'Новости Python'
        weather = weather_by_city(app.config['WEATHER_DEFAULT_CITY'])
        news_list = News.query.order_by(News.published.desc()).all()
        return render_template('index.html',
                               page_title=title,
                               weather_text=weather,
                               news_list=news_list)

    @app.route('/login')
    def login():
        title = 'Авторизация'
        login_form = LoginForm()
        return render_template('login.html', page_title=title, form=login_form)

    return app
Exemplo n.º 24
0
def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
    db.init_app(app)

    @app.route('/parse')
    def load_data():

        sub_categories = []
        catalogue = parse_handler('https://leroymerlin.ru/catalogue/',
                                  'div.items li', 'a span', 'a')

        for sub_category in catalogue[0:6]:
            sub_categories = sub_categories + parse_handler(
                sub_category['link'], 'div.items li', 'a span', 'a')

        for sub_category in sub_categories[0:6]:
            goods = parse_sub_category_page(sub_category['link'])

            for good in goods:
                row = Product(name=good.name,
                              url=good.url,
                              price=good.price,
                              weight=good.weight,
                              stock=good.stock,
                              id=good.id,
                              brand=good.brand,
                              category=sub_category['text'])
                db.session.add(row)
                db.session.commit()

        return '''{'status': 'ok'}'''

    @app.route('/')
    def home():
        data = Product.query.all()
        return render_template('home.html', data=data)

    return app
Exemplo n.º 25
0
def create_app():

    app=Flask(__name__)
    app.config.from_pyfile('../config.py')
    db.init_app(app)

    @app.route('/')
    def mainpage ():
        #message=test_db()
        return render_template('main.html')

    @app.route('/registration')
    def user_registration():
        pass

    @app.route('/login')
    def user_login():
        user_login_form=LoginForm()
        return render_template('Login.html', form=user_login_form)


    return app
Exemplo n.º 26
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)

    @app.route('/')
    def index():
        title = "Новости Python"
        weather = weather_by_city(app.config['WEATHER_DEFAULT_CITY'])
        news_list = get_python_news()
        return render_template('index.html',
                               page_title=title,
                               weather=weather,
                               news_list=news_list)

    @app.route('/login')
    def login():
        title = "Авторизация"
        login_form = LoginForm()
        return render_template('login.html', page_title=title, form=login_form)

    return app
Exemplo n.º 27
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)

    @app.route('/')
    def index():
        title = 'Python news'
        weather = weather_by_city(app.config["WEATHER_DEFAULT_CITY"])
        news_list = News.query.order_by(News.published.desc()).all(
        )  #запрашиваем все новости и сортируем по дате
        return render_template('index.html',
                               page_title=title,
                               weather=weather,
                               news_list=news_list)

    @app.route('/login')
    def login():
        title = "Авторизация"
        login_form = LoginForm()
        return render_template('login.html', page_title=title, form=login_form)

    return app
Exemplo n.º 28
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)

    @app.route('/submit_links', methods=['GET', 'POST'])
    def links_submission():
        title = "Добавление ссылок в БД"

        submit_a_link_form = SubmitForm()
        if submit_a_link_form.validate_on_submit():
            if request.method == 'POST':
                if request.form['action'] == 'one_more':
                    notice_urls.append(submit_a_link_form.a_link.data)
                    print(notice_urls)
                elif request.form['action'] == 'submit_all':
                    notice_urls.append(submit_a_link_form.a_link.data)
                    print(export_to_json(notice_urls))

        return render_template('links_submission.html',
                               page_title=title,
                               form=submit_a_link_form)

    return app
Exemplo n.º 29
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)

    @app.route('/')
    def index():
        spanish_form = SpanishForm()
        return render_template('index.html',
                               page_title="gogo!",
                               form=spanish_form)

    @app.route('/', methods=['POST'])
    def process_spanish():
        form = SpanishForm()
        if form.validate_on_submit():
            spanish_word = form.spanish_word.data
            english_words = form.english_words.data
            flash(spanish_word + english_words)
            return redirect(url_for('index'))
        flash('wrong data :(')
        return redirect(url_for('index'))

    return app
Exemplo n.º 30
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(
        app
    )  #инициализируем базу данных после конфигурации (т.к.нужен путь к sqlAlchemy)

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'login'

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)

    #http://api.worldweatheronline.com/premium/v1/weather.ashx?key=893cba22780d456aab894047200301&q=Moscow,Russia&format=json&num_of_days=1&lang=ru
    @app.route('/')  #декоратор
    def index():
        title = "Новости Python"
        weather = weather_by_city(app.config["WEATHER_DEFAULT_CITY"])
        news_list = News.query.order_by(News.published.desc()).all()
        #передаем название шаблона, Flask сам ищет папку template
        #шаблон занимается отображением, python получает данные для отображения
        return render_template('index.html',
                               page_title=title,
                               weather=weather,
                               news_list=news_list)

    @app.route('/login')
    def login():
        if current_user.is_authenticated:
            return redirect(url_for('index'))
        title = "Авторизация"
        login_form = LoginForm()
        return render_template('login.html', page_title=title, form=login_form)

    @app.route('/process-login', methods=['POST'])
    def process_login():
        form = LoginForm()
        if form.validate_on_submit():
            user = User.query.filter(
                User.username == form.username.data).first()
            if user and user.check_password(form.password.data):
                login_user(user)
                flash('Вы успешно вошли на сайт')
                return redirect(
                    url_for('index'))  #переадресация на главную страницу

        flash('Неправильное имя пользователя или пароль')
        return redirect(url_for('login'))  #переадресация на страниу логина

    @app.route('/logout')
    def logout():
        logout_user()
        flash('Вы успешно разлогинились')
        return redirect(url_for('index'))

    @app.route('/admin')
    @login_required  #еще один декоратор (оба декоратора обработаются перед вызовом нижеуказанной функции)
    def admin_index():
        if current_user.is_admin:
            return 'Привет админ!'
        else:
            return 'Вы не админ!'

    return app