Example #1
0
    def setUp(self):
        super(TestVitalInfo, self).setUp()

        db.add(Patient(nhi="123ABC"))
        db.add(VitalInfo(patient_nhi="123ABC", check_in_time=self.now))

        db.commit()
Example #2
0
def login():
    if request.method == "GET":
        return render_template("login.html")
    elif request.method == "POST":
        email = request.form.get("email")
        password = hashlib.sha256(request.form.get("password").encode("utf-8")).hexdigest()

        user = db.query(User).filter_by(email=email).first()

        if not user:
            user = User(password=password, email=email)
            db.add(user)
            db.commit()

        if password == user.password:
            # create a random session token for this user
            session_cookie = str(uuid.uuid4())

            # save the session token in a database
            user.session_token = session_cookie
            db.add(user)
            db.commit()

            response: Response = make_response(redirect(url_for('messenger', session_cookie=session_cookie)))
            # render template --> show html now on this url where you are; redirect move to new ur, make get request
            # there
            response.set_cookie("session_cookie", session_cookie, httponly=True, samesite='Strict')

            return response
        return redirect(url_for('login'))
Example #3
0
def result():
    guess = int(request.form.get("guess"))

    session_token = request.cookies.get("session_token")

    # get user from the database based on her/his email address
    user = db.query(User).filter_by(session_token=session_token).first()

    if guess == user.secret_number:
        message = "Correct! The secret number is {0}".format(str(guess))

        # create a new random secret number
        new_secret = random.randint(1, 30)

        # update the user's secret number
        user.secret_number = new_secret

        # update the user object in a database
        db.add(user)
        db.commit()
    elif guess > user.secret_number:
        message = "Your guess is not correct... try something smaller."
    elif guess < user.secret_number:
        message = "Your guess is not correct... try something bigger."

    return render_template("result.html", message=message)
def edit_profile():
    session_token = request.cookies.get("session_token")
    user = db.query(User).filter_by(session_token=session_token).first()

    if request.method == "GET":
        return render_template("edit_profile.html", user=user)
    elif request.method == "POST":
        name = request.form.get("profile-name")     #cogemos el nombre y el email del formulario y lo guardamos en estas variables
        email = request.form.get("profile-email")
        new_password = request.form.get("new_password")

        if len(new_password) > 6:
            hashed_new_password = hashlib.sha256(new_password.encode()).hexdigest()
            if hashed_new_password != user.password:
                user.password = hashed_new_password
            else:
                message1 = "This password is the same than the old one, please set a different one"
                return render_template("edit_profile.html", message1=message1, user=user)
        else:
            message2 = "Your password must be at least 6 characters long"
            return render_template("edit_profile.html", message2=message2, user=user)

        user.name = name    #asignamos el valor de la variable name y email a la propiedad user.name y user.email del objeto
        user.email = email
        db.add(user)                #guardamos los cambios en la base de datos
        db.commit()

        return redirect(url_for("bp_profile.profile"))
Example #5
0
    def login_exhentai(self, username, password):
        self.username = username.text
        self.password = password.text

        payload = {
            "UserName": username.text,
            "PassWord": password.text,
            "returntype": "8",
            "CookieDate": "1",
            "b": "d",
            "bt": "pone"
        }
        headers = {'User-Agent': 'Mozilla/5.0'}

        r = requests.post(
            "https://forums.e-hentai.org/index.php?act=Login&CODE=01",
            data=payload,
            headers=headers)

        if len(r.cookies) <= 1:
            captchapopup = CaptchaPopup()
            captchapopup.bind(on_dismiss=self.login_captcha)
            captchapopup.open()

        else:
            self.cookies = r.cookies
            cookies = User(cookies=str(self.cookies))
            db.add(cookies)
            db.commit()
            self.baseurl = "exhentai"
            self.next_screen("front_screen")
Example #6
0
    def get():
        """
        参数
        1.pub_id:酒吧id
        2.user_id: 登录用户id
        """
        parser = reqparse.RequestParser()
        parser.add_argument('pub_id', type=str, required=True, help=u'pub_id 必须')
        parser.add_argument('user_id', type=str, required=True, help=u'user_id 必须')

        args = parser.parse_args()

        success = success_dic().dic
        fail = fail_dic().dic

        pub_id = args['pub_id']
        user_id = args['user_id']

        collect = Collect.query.filter(Collect.user_id == user_id, Collect.pub_id == pub_id).first()
        try:
            db.delete(collect)
            db.commit()
            return success
        except:
            return fail
Example #7
0
def receipts(user_id):
    
    user = User.query.filter_by(id=user_id).first()

    if not user:
        return make_response("User " + str(user_id) + " doesn't exist", 404)

    if request.method == "POST":        
        if validate_request_receipt():
            receipt_date = date_string_to_datetime(request.json["date_time"])

            receipt = Receipt(request.json["store_name"],
                        request.json["category"],
                        request.json["total_transaction"],
                        receipt_date)

            user.receipts.append(receipt)

            for item in request.json["items"]:
                if validate_item(item):
                    item = PurchasedItem(item["name"],
                        request.json["category"],
                        item["price_per_item"],
                        item["quantity"])

                    receipt.purchased_items.append(item)


            db.add(user)
            db.commit()

            return json.dumps({"receipt": receipt.serialize()})

    else: #request is a get and return the receipts of the user
        return get_user_receipts(user)
def login_post():
    name = request.form.get("name")
    email = request.form.get("email")
    password = hashlib.sha512(
        request.form.get("password").encode()).hexdigest()
    print(password)
    number = randint(0, 10)
    print(number)
    user = db.query(User).filter_by(email=email).first()

    if user is not None:
        if user.password != password:
            return "<h1> Wrong Username or Password! </h1>"

    else:
        user = User(name=name,
                    email=email,
                    secret_number=number,
                    password=password,
                    token=str(uuid.uuid4()))
        db.add(user)
        db.commit()

    response = make_response(redirect(url_for("index")))
    response.set_cookie("token", user.token)

    return response
Example #9
0
def login():
    name = request.form.get("user-name")
    email = request.form.get("user-email")
    password = request.form.get("user-password")
    hashed_password = hashlib.sha256(password.encode()).hexdigest()

    secret_number = random.randint(1, 30)

    user = db.query(User).filter_by(email=email).first()

    if not user:
        user = User(name=name,
                    email=email,
                    secret_number=secret_number,
                    password=hashed_password)

        db.add(user)
        db.commit()

    if hashed_password != user.password:
        return "Wrong password! Please try again"

    elif hashed_password == user.password:
        session_token = str(uuid.uuid4())
        user.session_token = session_token
        db.add(user)
        db.commit()

        response = make_response(redirect(url_for('index')))
        response.set_cookie("session_token",
                            session_token,
                            httponly=True,
                            samesite="Strict")
        return response
Example #10
0
    def setUp(self):
        super(TestCheckIn, self).setUp()

        db.add(Patient(nhi="123ABC"))
        db.add(CheckIn(patient_nhi="123ABC", checkin_time=self.now))

        db.commit()
Example #11
0
    def get():
        """
            参数
                content: 反馈内容
                user_id: 登录用户id
        """
        parser = reqparse.RequestParser()
        parser.add_argument('content', type=str, required=True, help=u'content必须。')
        parser.add_argument('user_id', type=str, required=True, help=u'user_id必须。')

        args = parser.parse_args()

        resp_suc = success_dic().dic
        resp_fail = fail_dic().dic

        content = args['content']
        user_id = args['user_id']
        feed_back = FeedBack(content=content, user_id=user_id)

        try:
            db.add(feed_back)
            db.commit()
        except:
            return resp_fail
        return resp_suc
Example #12
0
def profile_edit():
    token_session = request.cookies.get("token_session")

    user = db.query(User).filter_by(token_session=token_session,
                                    delete=False).first()

    if request.method == "GET":
        if user:
            return render_template("profile_edit.html", user=user)
        else:
            return redirect(url_for("index"))

    elif request.method == "POST":
        name = request.form.get("profile-name")
        email = request.form.get("profile-email")
        old_password = request.form.get("old-password")
        new_password = request.form.get("new-password")

        if old_password and new_password:
            h_old_password = hashlib.sha256(old_password.encode()).hexdigest()
            h_new_password = hashlib.sha256(new_password.encode()).hexdigest()

            if h_old_password == user.password:
                user.password = h_new_password

            else:
                return "Operacion incorrecta! Su antigua contraseña no es correcta"

        user.name = name
        user.email = email

        db.add(user)
        db.commit()

        return redirect(url_for("profile"))
Example #13
0
    def get():
        """
            参数:
                user_id:用户登录id
        """
        parser = reqparse.RequestParser()
        parser.add_argument('user_id', type=str, required=True, help=u'user_id必须.')

        args = parser.parse_args()

        user_id = args['user_id']

        resp_suc = success_dic().dic
        resp_fail = fail_dic().dic

        message_count = Message.query.filter(Message.receiver_id == user_id).count()
        if message_count > 1:
            messages = Message.query.filter(Message.receiver_id == user_id).all()
            for message in messages:
                db.delete(message)
                try:
                    db.commit()
                except:
                    return resp_fail
            return resp_suc
        else:
            message = Message.query.filter(Message.receiver_id == user_id).first()
            db.delete(message)
            try:
                db.commit()
            except:
                return resp_fail
            return resp_suc
def login():
    name = request.form.get("user-name")
    email = request.form.get("user-email")
    password = request.form.get("user-password")
    hashed_password = hashlib.sha256(password.encode()).hexdigest()
    secret_number = random.randint(1, 30)
    user = db.query(User).filter_by(email=email).first()
    # user = User.fetch_one(query=["email", "==", email])
    if not user:
        user = User(name=name,
                    email=email,
                    secret_number=secret_number,
                    password=hashed_password)
        db.add(user)
        db.commit()
    if hashed_password != user.password:
        return "WRONG PASSWORD! Go back and try again"
    elif hashed_password == user.password:
        # generate random session number
        session_token = str(uuid.uuid4())
        user.session_token = session_token
        db.add(user)
        db.commit()

        response = make_response(redirect(url_for('index')))
        response.set_cookie("session_token",
                            session_token,
                            httponly=True,
                            samesite='Strict')
        return response
Example #15
0
 def enter_gallery(self, instance):
     galleryinfo = [instance.gallery_id, instance.gallery_token,
                    instance.pagecount, instance.gallery_name,
                    instance.gallery_tags, instance.gallery_thumb, instance.filesize]
     existgallery = db.query(Gallery).filter_by(
         gallery_id=instance.gallery_id).first()
     if existgallery:
         pass
     else:
         gallery = Gallery(gallery_id=instance.gallery_id,
                           gallery_token=instance.gallery_token,
                           pagecount=instance.pagecount,
                           gallery_name=instance.gallery_name,
                           gallery_thumb=instance.gallery_thumb,
                           filesize=instance.filesize)
         db.add(gallery)
         db.commit()
         for tag in instance.gallery_tags:
             gallerytag = GalleryTags(galleryid=gallery.id, tag=tag)
             db.add(gallerytag)
             db.commit()
     preview_screen = App.get_running_app(
     ).root.ids.sadpanda_screen_manager.get_screen("gallery_preview_screen")
     preview_screen.gallery_id = instance.gallery_id
     App.get_running_app().root.next_screen("gallery_preview_screen")
Example #16
0
def admin():
    global user

    chars = db.query(Character).all()
    users = db.query(User).all()
    db.commit()
    return render_template("/Nav-Pages/admin.html", users=users, chars=chars, admin=user.admin)
Example #17
0
def signup_post():
    email = request.form.get('email')
    name = request.form.get('name')
    password = request.form.get('password')
    gender = request.form.get('gender')
    address = request.form.get('address')
    contact = request.form.get('contact')

    user = db.query(User).filter_by(email=email).first(
    )  # if this returns a user, then the email already exists in database

    if user:  # if a user is found, we want to redirect back to signup page so user can try again
        flash('Email address already exists')
        return redirect(url_for('auth.signup'))

    # create new user with the form data. Hash the password so plaintext version isn't saved.
    new_user = User(email=email,
                    name=name,
                    password=generate_password_hash(password, method='sha256'),
                    gender=gender,
                    address=address,
                    contact=contact)

    # add the new user to the database
    db.add(new_user)
    db.commit()

    # code to validate and add user to database goes here
    return redirect(url_for('auth.login'))
Example #18
0
def login():
    name = request.form.get("name")
    password = request.form.get("password")

    hashed_pwd = hashlib.sha256(password.encode()).hexdigest()
    user = db.query(User).filter_by(name=name).first()

    if not user:
        flash(f"User doesn't exists. Please register.")
        return redirect(url_for("reg"))

    if hashed_pwd != user.password:
        flash(f"Wrong user name, email or password. Try again please.")
        return redirect(url_for("home"))

    else:
        session_token = str(uuid4())
        user.session_token = session_token
        user = User(online=True, offline=False)
        db.add(user)
        db.commit()

        response = make_response(redirect(url_for("home")))
        response.set_cookie("session_token", session_token)

        return response
Example #19
0
def index():
    if request.method == "GET":
        email_address = request.cookies.get("email")
        if email_address:
            user = db.query(User).filter_by(email=email_address).first()
        else:
            user = None
        return render_template("index.html", user=user)

    elif request.method == "POST":
        nombre = request.form.get("nombre")
        email = request.form.get("email")
        password = request.form.get("password")

        print(nombre)
        print(email)

        user = User(name=nombre, email=email, password=password)
        db.add(user)
        db.commit()

        response = make_response(redirect(url_for("index")))
        response.set_cookie("email", email)

        return response
Example #20
0
def delete():
    session_token = request.cookies.get("session_token")

    user = db.query(User).filter_by(session_token=session_token).first()

    if not user:
        return render_template(
            "home.html",
            user=user,
            location=location.title(),
            temperature=temperature,
            weather=weather,
        )

    if request.method == "POST":
        if user:
            db.delete(user)
            db.commit()

        response = make_response(redirect(url_for("home")))
        response.set_cookie("session_token", "")

        return response

    return render_template(
        "profile.html",
        user=user,
        location=location.title(),
        temperature=temperature,
        weather=weather,
    )
    def search_tag(self, instance):

        tag = instance.text
        search = Search(searchterm=tag)
        db.add(search)
        db.commit()
        App.get_running_app().root.next_screen("front_screen")
Example #22
0
def login():
    name = request.form.get("user-name")
    email = request.form.get("user-email")
    password = request.form.get("user-password")

    hash_pass = hashlib.sha256(password.encode()).hexdigest()

    user = db.query(User).filter_by(email=email).first()

    if not user:
        user = User(name=name, email=email, password=hash_pass)

        db.add(user)
        db.commit()

    if hash_pass != user.password:
        return "Contraseña incorrecta! Introduzca la contraseña correcta!"

    elif hash_pass == user.password:

        token_session = str(uuid.uuid4())

        user.token_session = token_session
        db.add(user)
        db.commit()

        response = make_response(redirect(url_for('index')))
        response.set_cookie("token_session",
                            token_session,
                            httponly=True,
                            samesite='Strict')

        return response
Example #23
0
def login():
    name = request.form.get("user-name")
    email = request.form.get("user-email")
    password = request.form.get("user-password")

    # hash the password
    hashed_password = hashlib.sha256(password.encode()).hexdigest()

    secret_number = random.randint(1, 30)

    # create a User object
    user = db.query(User).filter_by(email=email).first()

    if not user:        # create a user
        user = User(name=name, email=email, secret_number=secret_number, password=hashed_password)
        # save the user object into a database
        db.add(user)
        db.commit()
    if hashed_password != user.password:
        return "WRONG PASSWORD! Go back and try again."
    elif hashed_password == user.password:
        # create a random session token for this user
        session_token = str(uuid.uuid4())

        # save the session token in a database
        user.session_token = session_token
        db.add(user)
        db.commit()

        # save user's session token into a cookie
        response = make_response(redirect(url_for('index')))
        response.set_cookie("session_token", session_token)

        return response
Example #24
0
def bathymetry_coordinates_txt(id):
    """
    API endpoint to transform and store the posted X,Y,Z coordinates text blob in the specified bathymetry.

    :param id: bathymetry identifier
    :rtype: object
    """
    content = request.get_json(silent=True)
    print(content)
    # parse content
    f = StringIO(content.replace(' ', ''))
    result = read_coords(f)
    validate(instance=result, schema=schema)
    bathymetry = Bathymetry.query.get(id)
    if not bathymetry:
        raise ValueError("Invalid bathymetry with identifier %s" % id)
    BathymetryCoordinate.query.filter(
        BathymetryCoordinate.bathymetry_id == bathymetry.id).delete()
    for coordinate in result["coordinates"]:
        db.add(
            BathymetryCoordinate(x=coordinate["x"],
                                 y=coordinate["y"],
                                 z=coordinate["z"],
                                 bathymetry_id=bathymetry.id))

    db.commit()
    return jsonify(bathymetry.to_dict())
Example #25
0
    def search_tag(self, instance):

        tag = instance.text
        search = Search(searchterm=tag)
        db.add(search)
        db.commit()
        App.get_running_app().root.next_screen("front_screen")
Example #26
0
def result():
    guess = int(request.form.get("guess"))

    email_address = request.cookies.get("email")

    # Vadim Usera iz databaze po mailu
    user = db.query(User).filter_by(email=email_address).first()

    if guess == user.secret_number:
        message = "Correct! The secret number is {0}".format(str(guess))

        # Stvaram novi broj
        new_secret = random.randint(1, 30)

        # Updejtam Userov broj
        user.secret_number = new_secret

        # Updejtam objekt u databazi
        db.add(User)
        db.commit()

    elif guess > user.secret_number:
        message = "Your guess is not correct... try something smaller."

    elif guess < user.secret_number:
        message = "Your guess is not correct... try something bigger."

    return render_template("result.html", message=message)
Example #27
0
def register():
    user = check_login()
    if user:
        return redirect(url_for('index'))
    if request.method == "GET":
        return render_template("register.html", title="Register")
    elif request.method == "POST":
        name = request.form.get("username")
        email = request.form.get("email")
        raw_password = request.form.get("password")
        raw_password2 = request.form.get("passwordConf")

        if raw_password != raw_password2:
            return render_template("register.html",
                                   title="Register",
                                   diffPass=True)

        password = hashlib.sha3_256(raw_password.encode()).hexdigest()

        user = User(name=name, email=email, password=password)
        try:
            db.add(user)
            db.commit()
        except exc.IntegrityError:
            return render_template("register.html",
                                   title="Register",
                                   message=True)

        return log_in(user)
    else:
        return "Something is wrong."
Example #28
0
def edit_profile():
    session_token = request.cookies.get("session_token")

    user = db.query(User).filter_by(session_token=session_token, deleted=False).first()

    if request.method == "GET":
        if user:
            return render_template("profile_edit.html", user=user)
        else:
            return redirect(url_for("index"))
    elif request.method == "POST":
        name = request.form.get("profile-name")
        email = request.form.get("profile-email")
        prev_password = request.form.get("previous-password")
        new_password = request.form.get("new-password")

        if check_password_hash(user.password, prev_password):
            hashed_new_password = generate_password_hash(new_password)
            user.password = hashed_new_password
        else:
            return "Wrong (old) password! Go back and try again."

        user.name = name
        user.email = email

        db.add(user)
        db.commit()

        return redirect(url_for("show_profile"))
Example #29
0
def message_details(msg_id=None):
    if msg_id:
        msg = db.query(Mensaje).get(int(msg_id))

        if msg and msg.receiver == current_user.email:
            msg.read = True
            db.add(msg)
            db.commit()

            return render_template("messages.html",
                                   current_msg=msg,
                                   current_user=current_user)
        else:
            return "Message ID not valid!"
    else:
        messages = list(
            db.query(Mensaje).filter_by(receiver=current_user.email))

        messages.sort(key=lambda s: s.date)

        read = list(filter(lambda s: s.read, messages))
        non_read = list(filter(lambda s: not s.read, messages))

        for msg in non_read:
            msg.read = True
            db.add(msg)
            db.commit()

        return render_template("messages.html",
                               msg_read=read,
                               msg_non_read=non_read,
                               current_user=current_user)

    return render_template("messages.html", no_msg=True)
Example #30
0
def profile_edit():
    session_token = request.cookies.get("session_token")

    # get user from the database based on his / her session token from cookie "session_token"
    user = db.query(User).filter_by(session_token=session_token).first()

    if request.method == "GET":
        if user:  # if user is found
            return render_template("profile_edit.html", user=user)
        else:
            return render_template("index.html", user=user)

    elif request.method == "POST":
        name = request.form.get("profile-name")
        email = request.form.get("profile-email")
        password = request.form.get("profile-password")

        # hash the password
        hashed_password = hashlib.sha256(password.encode()).hexdigest()

        # update the user object
        user.name = name
        user.email = email
        user.password = hashed_password

        # store changes into the database
        db.add(user)
        db.commit()

        return redirect(url_for("profile"))
Example #31
0
    def get():
        """
        所需参数
            user_id: 必传,登录用户的id
            pub_id: 必传,用户点击收藏的当前酒吧的id
        """
        parser = reqparse.RequestParser()
        parser.add_argument('user_id', type=str, required=True, help=u'用户登录user_id必须。')
        parser.add_argument('pub_id', type=str, required=True, help=u'当前酒吧pub_id必须。')

        args = parser.parse_args()
        user_id = int(args['user_id'])
        pub_id = int(args['pub_id'])
        resp_suc = {}
        # 先判断用户是否已经收藏此酒吧
        check_collect = Collect.query.filter(Collect.user_id == user_id, Collect.pub_id == pub_id).count()
        if check_collect >= 1:
            resp_suc['message'] = 'again'
            resp_suc['status'] = 2
        else:
            collect = Collect(user_id, pub_id)
            db.add(collect)
            db.commit()
            resp_suc['message'] = 'success'
            resp_suc['status'] = 0
        return resp_suc
Example #32
0
def dashboard():
    form = Messageform()
    form.receiver_email.choices = get_choices(current_user)
    if request.method == "GET":
        messages = db.query(Mensaje).filter_by(receiver=current_user.email,
                                               read=False).all()
        users = db.query(User).all()
        return render_template("dashboard.html",
                               messages=messages,
                               form=form,
                               current_user=current_user,
                               users=users)

    else:
        if form.validate_on_submit():
            msg = Mensaje(subject=form.subject.data,
                          message=form.message.data,
                          receiver=form.receiver_email.data,
                          sender=current_user.email,
                          read=False)
            db.add(msg)
            db.commit()
            data = "Your message has been sent"
            return render_template("dashboard.html",
                                   data=data,
                                   form=form,
                                   current_user=current_user,
                                   msg=msg)
        else:
            data = "Error, review the entered data"
            return render_template("dashboard.html",
                                   data=data,
                                   form=form,
                                   current_user=current_user)
Example #33
0
def bathymetry_coordinates(id):
    """
    API endpoint to overwrite X,Y,Z coordinates for a specific bathymetry.

    :param id: bathymetry identifier
    :return:
    """
    content = request.get_json(silent=True)
    print(f"Content = {content}")
    validate(instance=content, schema=schema)
    bathymetry = Bathymetry.query.get(id)
    if not bathymetry:
        raise ValueError("Invalid bathymetry with identifier %s" % id)

    if len(content["coordinates"]) < 6:
        raise ValidationError(f"Coordinates Must be a minimum of 6")

    BathymetryCoordinate.query.filter(
        BathymetryCoordinate.bathymetry_id == bathymetry.id).delete()
    for coordinate in content["coordinates"]:
        db.add(
            BathymetryCoordinate(x=coordinate['x'],
                                 y=coordinate['y'],
                                 z=coordinate['z'],
                                 bathymetry_id=bathymetry.id))

    db.commit()
    return jsonify(bathymetry.to_dict())
def login():
    if request.method == "GET":
        return render_template("login.html")


    elif request.method== "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        hashed_pw = hashlib.sha256(password.encode()).hexdigest()

        # pregled ali user obstaja
        user = db.query(User).filter_by(username=username).first()

        if user:
            if hashed_pw == user.password:
                #Creating session token
                session_token = str(uuid.uuid4())
                user.session_token = session_token
                # db update with token
                db.add(user)
                db.commit()
                # cookie response
                response = make_response(redirect(url_for("index")))
                response.set_cookie("session_token", session_token, httponly=True, samesite="Strict")
                return response

            else:
                return render_template("failedlogin.html")
        else:
            return render_template("failedlogin.html")
Example #35
0
def add_receipt(num_receipts=1):
	user = User.query.first()

	days_ago_to_start = num_receipts/2
	date = datetime.now() - timedelta(days=days_ago_to_start)
	even_receipt = True

	for x in range(num_receipts):
		SHOP_NAME = "Countdown Birkenhead"
		SHOP_CATEGORY = "Groceries"
		TOTAL = 123.81
		r = Receipt(SHOP_NAME, SHOP_CATEGORY, TOTAL, date)
		r.purchased_items = [
			    PurchasedItem("Chocolate Milk", SHOP_CATEGORY, 3.99, 2),
			    PurchasedItem("Garlic Pita Breads", SHOP_CATEGORY, 4.50, 1),
			    PurchasedItem("Old Spice Deoderant", SHOP_CATEGORY, 6.21, 4),
			    PurchasedItem("Eye Fillet Steak", SHOP_CATEGORY, 21.4, 1),
			    PurchasedItem("Obikwa Wine 750mL", SHOP_CATEGORY, 6.99, 4),
			    PurchasedItem("North Shore Rubbish Sack", SHOP_CATEGORY, 4.99, 5),
			    PurchasedItem("Nutri-Grain 700g", SHOP_CATEGORY, 6.23, 1),
			    PurchasedItem("Olivio Butter", SHOP_CATEGORY, 5.95, 1)
       					 	]
		user.receipts.append(r)

		even_receipt = not even_receipt
		if even_receipt:
			date = date + timedelta(days=1)
		print len(user.receipts)

	db.add(user)
	db.commit()
Example #36
0
def patients():
    query = Patient.query.join(Department.patients).filter(
        Department.department_name == request.cookies.get('department', 'default'))

    if request.method == "GET":
        offset = int(request.args.get('offset', 0))
        limit = int(request.args.get('limit', 100))

        return make_response((json.dumps([
            p.serialize() for p in query
            .order_by(desc(Patient.latest_checkin_time))
            .offset(offset)
            .limit(limit)
            .all()
        ]), 200, {"Content-Type": "application/json"}))

    elif request.method == "POST":
        patient_data = json.loads(request.data)
        patient = Patient(**patient_data)
        patient = db.merge(patient)
        db.commit()

        department = Department.query.filter_by(
            department_name=request.cookies.get('department', 'default')).first()

        if department:
            patient.departments.append(department)

        db.commit()

        if 'checkin' in patient_data:
            add_checkin(patient.nhi, patient_data['checkin'])

        return jsonify(patient.serialize())
Example #37
0
    def login_exhentai(self, username, password):
        self.username = username.text
        self.password = password.text

        payload = {
            "UserName": username.text,
            "PassWord": password.text,
            "returntype": "8",
            "CookieDate": "1",
            "b": "d",
            "bt": "pone"
        }
        headers = {'User-Agent': 'Mozilla/5.0'}

        r = requests.post(
            "https://forums.e-hentai.org/index.php?act=Login&CODE=01",
            data=payload,
            headers=headers)

        if len(r.cookies) <= 1:
            captchapopup = CaptchaPopup()
            captchapopup.bind(on_dismiss=self.login_captcha)
            captchapopup.open()

        else:
            self.cookies = r.cookies
            cookies = User(cookies=str(self.cookies))
            db.add(cookies)
            db.commit()
            self.baseurl = "exhentai"
            self.next_screen("front_screen")
Example #38
0
def add_dia():

    t_hora_cita = request.form.get("hora_cita")
    titulo_cita = request.form.get("titulo_cita")
    notas_cita = request.form.get("notas_cita")
    year = request.form.get("cita_year")
    month = request.form.get("cita_month")
    day = request.form.get("cita_day")

    hora, minutos = convierte_hora(t_hora_cita)
    t_cita = year + "-" + month + "-" + day + "-" + hora + "-" + minutos
    hora_cita = datetime.strptime(
        t_cita, "%Y-%m-%d-%H-%M")  # convierto del formato texto al datetime

    user = db.query(User).filter_by(username=session["username"]).first()

    cita = Cita(fecha=hora_cita,
                titulo=titulo_cita,
                notas=notas_cita,
                user_id=user.id)

    db.add(cita)
    db.commit()

    return redirect(url_for('dia', month=month, year=year, day=day))
Example #39
0
def login():
    name = request.form.get("user-name")
    email = request.form.get("user-email")
    password = request.form.get("user-password")

    # create a secret number
    secret_number = random.randint(1, 30)

    # see if user already exists
    user = db.query(User).filter_by(email=email).first()

    if not user:
        # create a User object
        user = User(name=name, email=email, password=generate_password_hash(password), secret_number=secret_number)

        # save the user object into a database
        db.add(user)
        db.commit()

    if not check_password_hash(user.password, password):
        return "Sorry, your password is not correct."

    session_token = str(uuid.uuid4())
    user.session_token = session_token

    db.add(user)
    db.commit()

    # save user's token into a cookie
    response = make_response(redirect(url_for('index')))
    response.set_cookie("session_token", session_token, httponly=True, samesite="Strict")

    return response
Example #40
0
def profile_edit():
    session_token = request.cookies.get("session_token")

    # get user from the database based on her/his email address
    user = db.query(User).filter_by(session_token=session_token).first()

    if request.method == "GET":
        if user:  # if user is found
            return render_template("profile_edit.html", user=user)
        else:
            return redirect(url_for("index"))

    elif request.method == "POST":
        name = request.form.get("profile-name")
        email = request.form.get("profile-email")

        # update the user object
        user.name = name
        user.email = email

        # store changes into the database
        db.add(user)
        db.commit()

        return redirect(url_for("profile"))
def edit():

    # find user
    session_token = request.cookies.get("session_token")
    user = db.query(User).filter_by(session_token=session_token).first()

    if request.method == "GET":
        return render_template("edit.html", user=user)


    elif request.method == "POST":

        #username change
        username = request.form.get("username")
        if len(username) > 0:
            user.username = username

        #email change
        email    = request.form.get("user-email")
        if len(email) > 0:
            user.email = email

        #password change
        password = request.form.get("password")
        passwordtest = request.form.get("password-repeat")
        if (len(password) > 0) and (password == passwordtest):
            hashed_pw = hashlib.sha256(password.encode()).hexdigest()
            user.password = hashed_pw

        db.add(user)
        db.commit()

        return redirect((url_for("edit")))
Example #42
0
def congress():

    url = 'http://www.globaleventslist.elsevier.com/controls/events_list_control.ashx?a=true&_t='
    page = 0
    n_congress = 0
    print(f'Started populate congress at: {datetime.datetime.now()}')
    while True:
        page += 1
        print(f'Request page {page}')
        payload = {'page': page, 'sortBy': 'recency'}
        response = requests.post(url + str(int(time.time())), payload)
        conferences = json.loads(response.text)['results']
        if (page % 10) == 0:
            db.commit()
            print(f'committed : {page}')
            print(f'insert {n_congress} rows')
        if len(conferences) <= 0:
            db.commit()
            print(
                f'{datetime.datetime.now()}- Finished, populated with {n_congress} congress'
            )
            break

        for conference in conferences:
            name = conference['Name']
            data_str = re.search('(\d+)', conference['DateStart']).group(1)
            submission_deadline = datetime.datetime.fromtimestamp(
                int(data_str[:10]))
            review_deadline = submission_deadline + datetime.timedelta(days=10)

            Congress.get_or_create(
                name=name,
                submissionDeadline=submission_deadline.date(),
                reviewDeadline=review_deadline.date())
            n_congress += 1
Example #43
0
def save_pub_type(pub_id, types):
    """保存酒吧类型"""

    type_list = [int(i) for i in types.split(",")]
    for pub_type in type_list:
        db.add(PubTypeMid(pub_id, pub_type))

    db.commit()
Example #44
0
def direct_message_count(direct_message):
    if type(direct_message) is list:
        for message in direct_message:
            message.view = 1
            db.commit()
    else:
        direct_message.view = 1
        db.commit()
Example #45
0
    def process_item(self, item, spider):

        # create a new SQL Alchemy object and add to the db session
        record = AllData(title=item['title'][0].decode('unicode_escape'),
                         url=item['url'][0],
                         desc=item['desc'])
        db.add(record)
        db.commit()
        return item
Example #46
0
def message_type(user_id, system_message):
    user = User.query.filter(User.id == user_id).first()
    if type(system_message) is list:
        user.system_message_time = todayfstr()
        db.commit()
    else:
        if system_message:
            user.system_message_time = todayfstr()
            db.commit()
Example #47
0
def new_smartcard(user):
	if validate_smartcard():
		user.smartcard = Smartcard(request.json["smartcard_number"], request.json["enabled"])
		db.add(user)
		db.commit()
		return json.dumps(user.smartcard.serialize())

	else:
		return make_response("Incorrect data in JSON", 400)
Example #48
0
def update_smartcard_status(smartcard):
	if not "enabled" in request.json:
		return make_response("Incorrect data in json", 400)

	smartcard.enabled = request.json["enabled"]
	db.add(smartcard)
	db.commit()

	return json.dumps(smartcard.serialize())
Example #49
0
    def populate_gallery(self):
        # change placehold.it with
        gallerypages = float(self.pagecount) / float(40)
        pageregex = re.compile('http://' + App.get_running_app().root.baseurl +
                               '.org/s/\S{10}/\d{6}-\d+')

        if gallerypages.is_integer():
            pass
        else:
            gallerypages += 1

        headers = {'User-agent': 'Mozilla/5.0'}
        cookies = App.get_running_app().root.cookies
        for i in range(int(gallerypages)):
            galleryrequest = requests.get(
                "http://" + App.get_running_app().root.baseurl +
                ".org/g/{}/{}/?p={}\
                                          "
                .format(self.gallery_id, self.gallery_token, i),
                headers=headers,
                cookies=cookies)

            soup = BS(galleryrequest.text)

            for a in soup.findAll(name="a", attrs={"href": pageregex}):
                self.pagelinks.append(a["href"])
                existpageurl = db.query(Pagelink).filter_by(
                    pagelink=a["href"]).first()
                if existpageurl:
                    pass
                else:
                    pageurl = Pagelink(galleryid=self.db_id,
                                       pagelink=a["href"])
                    db.add(pageurl)
                    db.commit()

        # pagetimer = 0
        # for page in self.pagelinks:
        #   Clock.schedule_once(partial(self.grab_image, page), 2*pagetimer)
        #    pagetimer += 1

        self.next_page = 1

        currentexist = db.query(Pagelink).filter_by(galleryid=self.db_id,
                                                    current=1).first()
        if currentexist:
            first_screen = self.construct_image(currentexist.pagelink)
            self.ids.gallery_manager.switch_to(first_screen)
        else:
            first_screen = self.construct_image(self.pagelinks[0])
            self.ids.gallery_manager.switch_to(first_screen)
            # consider adding this in its own thread
            firstimage = db.query(Pagelink).filter_by(
                pagelink=self.pagelinks[0]).first()
            firstimage.current = 1
            db.commit()
Example #50
0
def add_vital_info(nhi, data):
    v = VitalInfo(**data)
    v.patient_nhi = nhi

    db.add(v)
    db.commit()

    if v.patient.latest_check_in is None or v.check_in_time > v.patient.latest_check_in:
        v.patient.latest_check_in = v.check_in_time

    db.commit()
    return v
Example #51
0
def save_activity_thumbnail(picture_id):
    """通过图片ID,查找图片,生产略缩图,存储本地,然后存储数据库"""

    activity_picture = ActivityPicture.query.filter(ActivityPicture.id == picture_id).first()
    save_path = activity_picture.base_path + activity_picture.rel_path + '/'
    picture = save_path + activity_picture.pic_name
    im = Image.open(picture)
    im.thumbnail((256, 256))
    thumbnail_name = time_file_name(activity_picture.upload_name, sign='nail') + '.jpeg'
    im.save(save_path+thumbnail_name, 'jpeg')
    activity_picture.thumbnail = thumbnail_name
    db.commit()
Example #52
0
def add_checkin(nhi, data):
    c = CheckIn(**data)
    c.patient_nhi = nhi

    db.add(c)
    db.commit()

    if c.patient.latest_checkin_time is None or c.checkin_time > c.patient.latest_checkin_time:
        c.patient.latest_checkin_time = c.checkin_time

    db.commit()
    return c
Example #53
0
def user_put(user):
	for key in request.json.keys():
		if key == "id":
			pass
		elif hasattr(user, key):
			setattr(user, key, request.json[key])

	user.generate_gravatar_url()

	db.add(user)
	db.commit()

	return json.dumps({"user": user.serialize()})
def spending_category_put(sc):
  print request.json

  if "category_name" in request.json:
    sc.category_name = request.json["category_name"]

  if "monthly_allowance" in request.json:
    sc.monthly_allowance = request.json["monthly_allowance"]

  db.add(sc)
  db.commit()

  return json.dumps(sc.serialize())
Example #55
0
def patient(nhi):
    patient = Patient.query.filter_by(nhi=nhi).first()

    if not patient:
        return make_response("No patient with NHI " + nhi, 404)

    elif request.method == "GET":
        return jsonify(patient.serialize())

    elif request.method == "DELETE":
        db.delete(patient)
        db.commit()

        return make_response("Deleted patient: {}".format(nhi), 200)
Example #56
0
def receipt(user_id, receipt_id):
    user = User.query.filter_by(id=user_id).first()
    receipt = Receipt.query.filter_by(id=receipt_id).first()

    if not user or not receipt or not user == receipt.user:
        return make_response("404 coming your way", 404)

    if request.method == "GET":
        return json.dumps({"receipt" : receipt.serialize_with_items()})
    elif request.method == "DELETE":
        db.delete(receipt)
        db.commit()

        return json.dumps({})
Example #57
0
def register_view():
    register_form = RegisterForm(request.form)
    if helpers.validate_form_on_submit(register_form):
        user = User(login_name=register_form.email.data, password=register_form.password.data,
                    login_type=0, nick_name=register_form.login.data)
        db.add(user)
        db.commit()

        login_user_with_remember(user)
        if user.admin:
            return redirect('/admin')

        return redirect('/admin')

    return render_template('admin_pub/auth.html', form=register_form)
 def add_favourite(self, *args):
     existfavourite = db.query(Favourites).filter_by(gallery_id=self.gallery_id).first()
     if existfavourite:
         return
     else:
         newfav = Favourites()
         newfav.gallery_id = self.gallery_id
         newfav.gallery_token = self.gallery_token
         newfav.pagecount = self.pagecount
         newfav.gallery_name = self.gallery_name
         newfav.gallery_thumb = self.gallery_thumb
         newfav.filesize = self.filesize
         db.add(newfav)
         db.commit()
         Snackbar.make("Added to favourites!")
Example #59
0
def save_pub_pictures(pub_id, pictures):
    """保存酒吧图片"""
    for picture in pictures:
        if not allowed_file_extension(picture.filename, PUB_PICTURE_ALLOWED_EXTENSION):
            continue
        else:
            upload_name = picture.filename
            base_path = PUB_PICTURE_BASE_PATH
            rel_path = PUB_PICTURE_UPLOAD_FOLDER
            pic_name = time_file_name(secure_filename(upload_name), sign=pub_id)
            pub_picture = PubPicture(pub_id, base_path, rel_path, pic_name, upload_name, cover=0)
            db.add(pub_picture)
            picture.save(os.path.join(base_path + rel_path + "/", pic_name))
            db.commit()
            save_thumbnail(pub_picture.id)
Example #60
0
def save_activity_pictures(activity_id, pictures):
    """保存酒吧图片"""
    for picture in pictures:
        if not allowed_file_extension(picture.filename, ACTIVITY_PICTURE_ALLOWED_EXTENSION):
            continue
        else:
            upload_name = picture.filename
            base_path = ACTIVITY_PICTURE_BASE_PATH
            rel_path = ACTIVITY_PICTURE_UPLOAD_FOLDER
            pic_name = time_file_name(secure_filename(upload_name), sign=activity_id)
            activity_picture = ActivityPicture(activity_id, base_path, rel_path, pic_name, upload_name, cover=0)
            db.add(activity_picture)
            picture.save(os.path.join(base_path+rel_path+'/', pic_name))
            db.commit()
            save_thumbnail(activity_picture.id)