from multiprocessing import Process
from flask import Flask
from aiogram import Bot, Dispatcher, executor, types
import config
app = Flask(import_name=__name__)
bot = Bot(token=config.BOT_TOKEN)
dispatcher = Dispatcher(bot=bot)
def bot_start_polling():
executor.start_polling(dispatcher=dispatcher, skip_updates=True)
@dispatcher.message_handler(commands=['start'])
async def bot_handler_start(message: types.Message):
await message.reply('Foo')
@app.get(rule='/start_bot')
def start_bot():
bot_process = Process(target=bot_start_polling)
bot_process.start()
return str(bot_process.pid)
if __name__ == '__main__':
app.run()
@app.route('/result')
def result():
username = request.args.get('username')
ok_message=''
reject_message=''
uppercase_err_message=''
num_err_message=''
has_upper = any([i.isupper() for i in username])
has_digit = any([i.isdigit() for i in username])
if not has_upper:
uppercase_err_message = 'Need an UPPERCASE'
elif not has_digit:
num_err_message = 'need a NUM'
if has_upper and has_digit:
ok_message = 'ALL GOOD!'
else:
reject_message = 'NOT GOOD...'
return render_template(
'result.html',
username=username,
ok_message=ok_message,
reject_message=reject_message,
uppercase_err_message=uppercase_err_message,
num_err_message=num_err_message
)
if request.method == 'POST':
username = request.form.get('username') # запрос к данным формы
password = request.form.get('password')
if username == 'root' and password == 'pass':
message = "Correct username and password"
else:
message = "Wrong username or password"
id
а к текстовому поля указатель на форму:<label>
<textarea name="recipe" rows="15" cols="55" form="some-form"></textarea>
</label>
<form id="some-form" action="/save" method="POST">
<input type="submit" value="Сохранить">
</form>
import logging
@app.route('/create-poem/', methods=['POST', 'GET'])
def create():
if request.method == 'POST':
...
try:
...
except Exception:
logging.exception('')
return ''
else:
...
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: ivan
db.create_all()
app.run(debug=True)
ru_riddles = riddles.query.filter(riddles.ruText.ilike(q)).all()
@app.route(rule='/<foo>/<bar>', methods=['GET'])
def index(foo, bar):
....
foo
и bar
- это параметры адреса, то есть example.com/asda/dasda
. Если тебе нужно получить аргументы адреса, например example.com/?foo=asda
, то нужно использовать request.args
, то есть:from flask import request
@app.route(rule='/', methods=['GET'])
def index():
if request.args.get('foo'):
return f'{request.args["foo"]}'
....
from flask import Flask, request, jsonify
from flask_jwt_extended import (
JWTManager,
create_access_token,
jwt_required,
get_jwt_identity
)
app = Flask(__name__)
app.config['SECRET_KEY'] = 'super-secret'
app.config['JWT_SECRET_KEY'] = app.config['SECRET_KEY']
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = False
jwt = JWTManager(app)
users = ['kshnkvn']
@app.route('/login', methods=['POST'])
def login():
user = request.json.get('user')
if user not in users:
return jsonify(
{'status': False, 'result': 'User not exists'})
else:
return jsonify(
{'status': True, 'result': create_access_token(identity=user)})
@app.route('/user', methods=['GET'])
@jwt_required
def user():
user = get_jwt_identity()
return jsonify({'status': True, 'result': user})
if __name__ == '__main__':
app.run(debug=True, port=6061)
/user
без заголовка с авторизацией, то получаем в ответ:{
"msg": "Missing Authorization Header"
}
POST
запрос на /login
где в теле запроса отправляем JSON
с именем пользователя, а в ответ получаем токен:{
"status": true,
"result": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MDYzOTk0NjcsIm5iZiI6MTYwNjM5OTQ2NywianRpIjoiMTgxZmY2ZGQtN2FmNS00ZTUxLTlhMzAtODA3MTNhYzNlZGJlIiwiaWRlbnRpdHkiOiJrc2hua3ZuIiwiZnJlc2giOmZhbHNlLCJ0eXBlIjoiYWNjZXNzIn0.DwzxBd-6Hz1Gg6O-7JIoFrBm_XzCoiOD6xIRhFUjG0Q"
}
"Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MDYzOTk0NjcsIm5iZiI6MTYwNjM5OTQ2NywianRpIjoiMTgxZmY2ZGQtN2FmNS00ZTUxLTlhMzAtODA3MTNhYzNlZGJlIiwiaWRlbnRpdHkiOiJrc2hua3ZuIiwiZnJlc2giOmZhbHNlLCJ0eXBlIjoiYWNjZXNzIn0.DwzxBd-6Hz1Gg6O-7JIoFrBm_XzCoiOD6xIRhFUjG0Q"
и заходим на нужную ссылку, например для /user
будет следующий ответ:{
"status": true,
"result": "kshnkvn"
}
from datetime import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'
app.config['SQLALCHEMY_BINDS'] = {
'messages': 'sqlite:///message.db'
}
db = SQLAlchemy(app)
class Article(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
intro = db.Column(db.String(300), nullable=False)
text = db.Column(db.Text, nullable=False)
date = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return '<Article %r>' % self.id
class Message(db.Model):
__bind_key__ = 'messages'
id = db.Column(db.Integer, primary_key=True)
Name = db.Column(db.Text, nullable=False)
Surname = db.Column(db.Text, nullable=False)
text = db.Column(db.Text, nullable=False)
date = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return '<Message %r>' % self.Name
@app.route('/add_message')
def add_message():
message = Message(Name='name', Surname='surname', text='foo')
db.session.add(message)
db.session.commit()
return 'True'
db.create_all()
db.create_all(bind='messages')
if __name__ == '__main__':
app.run(debug=1)
from flask import session
@app.route('/')
def index():
if not session.get('logged_in'):
return redirect('/submit')
else:
return render_template('index.html')
@app.route('/submit', methods = ['POST'])
def post():
if request.form.get('login') == 'admin':
session['logged_in'] = True
return jsonify({'type':'success','msg':'success'})
return jsonify({'type':'error','msg':'error'})