def register(): if current_user.is_authenticated: return redirect(url_for("home")) if request.method == "GET": return render_template("auth/register.html", user=current_user) username = request.form.get("username") password = request.form.get("password") if not (username and len(username) >= 3 and password and len(password) >= 4): return render_template( "auth/register.html", error_text="Username has to be at least 3 symbols and pass min 5", user=current_user, ) if Session.query(User).filter_by(username=username).count(): return render_template( "auth/register.html", error_text=f"Username {username!r} already exists!", user=current_user, ) user = User(username, password) Session.add(user) try: Session.commit() except Exception as e: logger.exception("Error creating user!") raise InternalServerError(f"Could not create new user! Error: {e}") login_user(user) return redirect(url_for("home"))
class BaseHandler(tornado.web.RequestHandler, SessionMixin): def get_current_user(self): return self.session.get('username_session') def initialize(self): self.db_session = Session() self.orm = OrmHandler(self.db_session) def on_finish(self): self.db_session.close()
def get(self, user_id): session = Session() rows = session.query(User).filter_by(id=user_id).first() session.delete(rows) session.commit() session.close() self.redirect('/administrator')
def get(self, quote_id): session = Session() rows = session.query(Quotes).filter_by(id=quote_id).first() session.delete(rows) session.commit() session.close() self.redirect('/quotes')
def registration(): form = RegistrationForm() if request.method == "POST" and form.validate(): user = User(username=form.username.data, password=form.password.data) Session.add(user) Session.commit() flash(message=f'Пользователь {user.username} успешно зарегистрирован', category='success') return redirect(url_for("auth_app.login")) return render_template("auth/registration.html", form=form)
def update_post(post_id): post = Session.query(Post).filter_by(id=post_id).first() form = PostForm(obj=post) if request.method == "POST" and form.validate(): post.title = request.form.get('title') post.text = request.form.get('text') post.image_url = request.form.get('image_url') Session.commit() return redirect(url_for("main")) return render_template("posts/update.html", form=form, post_id=post.id)
class BaseHandler(tornado.web.RequestHandler, SessionMixin): def get_current_user(self): return self.session.get('tudo_user', None) def prepare(self): self.db_session = Session() logger.info('db_session instance {}'.format(self)) self.orm = HandlerORM(self.db_session) def on_finish(self): self.db_session.close() logger.info('db_session close')
def add_post(img_url, thumb_url, username): session = Session() user = session.query(User).filter_by(username=username).first() post = Post(image_url=img_url, thumb_url=thumb_url, user_id=user.id) session.add(post) session.commit() post_id = post.id session.close() return post_id
def create_post(): form = PostForm() if request.method == "POST" and form.validate(): post = Post( title=request.form.get('title'), text=request.form.get('text'), image_url=request.form.get('image_url'), user_id=current_user.id ) Session.add(post) Session.commit() return redirect(url_for("main")) return render_template("posts/create.html", form=form)
def new_post(): if not current_user.is_authenticated: return redirect(url_for("index.html")) if request.method == "GET": return render_template("new_post.html") form = request.form post_text = form['post_text'] post = Post(post_text, current_user.id) Session.add(post) try: Session.commit() except Exception as e: logger.exception("Error creating post!") raise InternalServerError(f"Could not create new post! Error: {e}") return redirect(url_for("index"))
class UserManager: _DB = Session() @classmethod def find(cls, user_id: int) -> User: return cls._DB.query(User).get(user_id) @classmethod def get(cls) -> List[User]: return cls._DB.query(User).all() @classmethod def get_by_email(cls, email: str) -> User: return cls._DB.query(User).filter_by(email=email).first() @classmethod def save(cls, data) -> User: password = Crypt.hash(data.password) user = User(email=data.email, password=password) cls._DB.add(user) cls._DB.commit() return user @classmethod def delete(cls, user_id: int) -> bool: user = cls.get_user(user_id) if not user: return False cls._DB.delete(user) cls._DB.commit() return True
def get_all_posts(username=None): ''' 查询获取所有图片或者是特定的用户 :param username:如果没做,就是获取全部图片 :return: ''' session = Session() if username: user = session.query(User).filter_by(username=username).first() posts = session.query(Post).filter_by(user=user).all() else: posts = session.query(Post).all() if posts: return posts else: return []
def login(): form = LoginForm() if request.method == "POST" and form.validate(): user = Session.query(User).filter_by( username=form.username.data).first() login_user(user) return redirect(url_for("main")) return render_template("auth/login.html", form=form)
def sign_in(): if current_user.is_authenticated: return redirect(url_for("index")) if request.method == "GET": return render_template("sign_in.html") username, password = get_username_and_password_from_form(request.form) validate_username_unique(username) user = User(username, password) Session.add(user) try: Session.commit() except Exception as e: logger.exception("Error creating user!") raise InternalServerError(f"Could not create new user! Error: {e}") login_user(user) return redirect(url_for("index"))
def post(self, quote_id): author = self.get_argument('author', '') country = self.get_argument('country', '') content = self.get_argument('content', '') session = Session() session.query(Quotes).filter_by(id=int(quote_id)).update({Quotes.author: author, Quotes.country: country,Quotes.quotes_content: content}) session.commit() self.redirect('/quotes')
def login(): if current_user.is_authenticated: return redirect(url_for("index.html")) if request.method == "GET": return render_template("login.html") username, password = get_username_and_password_from_form(request.form) user = Session.query(User).filter_by(username=username).one_or_none() if not user: return render_template("login.html", error_text="User not found") if user.password != User.hash_password(password): return render_template("login.html", error_text="Invalid username or password!") login_user(user) print("Uid:", user.id) return redirect(url_for("index"))
def add_post(): if request.method == "GET": return render_template("post/add_post.html", user=current_user) title = request.form["title"] text = request.form["text"] if not title: return render_template( "post/add_post.html", error_text="Title can't be empty", user=current_user ) if not text: return render_template( "post/add_post.html", error_text="Text can't be empty", user=current_user ) new_post = Post(title, text, current_user.id) Session.add(new_post) try: Session.commit() except Exception as e: logger.exception("Error creating post!") raise InternalServerError(f"Could not create new post! Error: {e}") return redirect(url_for("home"))
def register(username, password1, password2): ret = {'msg': 'other error', 'user_id': None} if username and password1 and password2: if password1 == password2: session = Session() user = session.query(User).filter_by(username=username).all() if user: msg = 'username is exists' else: new_user = User(username=username, password=hash(password1)) session.add(new_user) session.commit() ret['user_id'] = new_user.id session.close() msg = 'ok' else: msg = 'password1 != password2' else: msg = 'username or password is empty' ret['msg'] = msg return ret
def post(self, user_id): username = self.get_argument('username', '') password = self.get_argument('password', '') email = self.get_argument('email', '') gender = self.get_argument('gender', '') age = self.get_argument('age', ' ') power = self.get_argument('power', '') session =Session() session.query(User).filter_by(id=int(user_id)).update({User.username: username, User.password: password, User.emial: email, User.gender: gender, User.age: age,User.power: int(power)}) session.commit() self.redirect('/administrator')
def post(self): username = self.get_argument('username', '') username1 = self.get_argument('username1', '') password = self.get_argument('password', '') email = self.get_argument('email', '') gender = self.get_argument('gender', '') age = self.get_argument('age', ' ') session = Session() dict_data = {User.username:username1,User.password:password, User.emial:email,User.gender:gender,User.age:age} session.query(User).filter_by(username=username).update(dict_data) session.commit() self.redirect('/')
def login(): if current_user.is_authenticated: return redirect(url_for("home")) if request.method == "GET": return render_template("auth/login.html", user=current_user) username = request.form.get("username") password = request.form.get("password") user = Session.query(User).filter_by(username=username).one_or_none() if not user: return render_template("auth/login.html", error_text="User not found") if user.password != User.hash_password(password): return render_template( "auth/login.html", error_text="Invalid username or password!", user=current_user, ) login_user(user) return redirect(url_for("home"))
def is_exists(cls, username, password): session = Session() ret = session.query(exists().where( and_(User.name == username, User.password == password))).scalar() session.close() return ret
def validate_username(self, field): if len(field.data) < 6: field.errors.append('Логин должен быть не менее 6 символов') if Session.query(User).filter_by(username=field.data).first(): field.errors.append( 'Пользователь с таким логином уже зарегистрирован')
def get_user(self, username): return Session.query(User).filter_by(username=username).first()
def remove_session(*args): Session.remove()
def main(): posts = Session.query(Post).order_by(Post.created) return render_template("index.html", posts=posts)
def load_user(user_id): return Session.query(User).filter_by(id=user_id).one_or_none()
from datetime import datetime from sqlalchemy import Column, Integer, String, DateTime, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.sql import exists from models.db import Base, Session session = Session() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True, autoincrement=True) username = Column(String(50), unique=True, nullable=False) password = Column(String(50)) creatime = Column(DateTime, default=datetime.now) email = Column(String(80)) def __repr__(self): return "<User表:id:{},username:{}>".format(self.id, self.username) @classmethod # 定义一个查询用户是否存在的方法 def is_exists(cls, username): return session.query(exists().where(cls.username == username)).scalar() @classmethod def get_password(cls, username): user = session.query(cls).filter_by(username=username).first() if user: return user.password
def initialize(self): self.db_session = Session() self.orm = OrmHandler(self.db_session)
import hashlib from models.auth import User, Post, Like from models.db import Session db_session = Session() def hashed(text): """ 密码md5加密 :param text: password :return: """ return hashlib.md5(text.encode('utf8')).hexdigest() def authenticate(username, password): """ 验证密码 :param username: :param password: :return: """ return User.get_password(username) == hashed(password) # 返回bool值 class HandlerORM: """ 辅助操作数据库的工具类, 综合 RequestHandler使用 """ def __init__(self, db_session):