Ejemplo n.º 1
0
    def do_GET(self):
        """GETEXTERNAL, PATCH_DELETE_GET allowed"""
        url_data = self.check_url()
        if not url_data:
            self.send_status(404)
            return

        # allowed 3 kind of operations for GET request: get from external source, get of one row by ID, get all rows
        if url_data['command'] not in (GETEXTERNAL, PATCH_DELETE_GET,
                                       POSTCREATE_GETALL):
            self.send_status(400)
            return

        if url_data['command'] == GETEXTERNAL:
            result = model.get_external_data(url_data['data'])
            self.send_status(200)
            self.send_result(200, result)
        elif url_data['command'] == PATCH_DELETE_GET:
            # get data from database and url_data['data'] will be an id in our database
            conn = model.db_connect(DBNAME)

            id = int(url_data['data'])
            self._get_books(conn, id)
        else:  # POSTCREATE_GETALL case, here it will return all records from DB
            conn = model.db_connect(DBNAME)

            self._get_books(conn)
Ejemplo n.º 2
0
def redirect_on_code(code):
	try:
		model.db_connect()
		model.log_visit(code)
		url = model.url_info(code)
		model.db.close()
		return redirect(url.url)
	except:
		model.db.close()
		return render_template('404.html'), 404
Ejemplo n.º 3
0
	def test_create_code(self):
		#due to the not so great nature of adding false entries to 
		#the database, I'm grouping a few tests here
		model.db_connect()
		less = model.db.query(func.count(Url.code)).first()
		code = model.create_code(self.url)
		greater = model.db.query(func.count(Url.code)).first()
		self.assertGreater(greater, less)
		self.assertEqual(len(code), 6)
		model.db.query(Url).filter_by(code=code).delete()
		model.db.commit()
Ejemplo n.º 4
0
    def create_account():
        if flask.request.method == "GET":
            return flask.render_template("create-account.html", errors=[])
        else:
            assert flask.request.method == "POST"
            form = flask.request.form

            user_name = form["username"]
            password_1 = form["password1"]
            password_2 = form["password2"]
            email_id = form["email"]

            errors = []

            # Checking if the username is unique:
            with model.db_connect() as connection:
                if model.users.check_if_username_exists(connection, user_name):
                    errors.append(
                        f"A user with the username '{user_name}' already exists. "
                        f"Please try a different username.")

            if password_1 != password_2:
                errors.append(
                    f"The two passwords you entered do not match. Please try re-entering them."
                )

            if errors:
                return flask.render_template("create-account.html",
                                             errors=errors)
            else:
                # Create the account.
                assert password_1 == password_2
                try:
                    with model.db_connect() as connection:
                        model.users.create_user(connection, user_name,
                                                email_id, password_1)
                except model.sqlite3.DatabaseError:
                    return flask.render_template(
                        "create-account.html",
                        errors=[
                            "A server error occurred. Please try creating your account again. "
                            "(Database insertion failed)."
                        ])
                # CREATE EMAIL TOKEN and Email it with
                token = s.dumps(email_id)
                link = flask.url_for('confirm_email',
                                     token=token,
                                     _external=True)
                mailgun_func(email_id, link)
                flash(
                    "We\'ve sent a confirmation email to {} check your spam folder"
                    .format(email_id))
                return flask.redirect(flask.url_for('index'))
Ejemplo n.º 5
0
    def do_POST(self):
        url_data = self.check_url()
        if not url_data:
            self.send_status(404)
            return

        if url_data['command'] not in (POSTCREATE_GETALL, POSTUPDATE,
                                       POSTDELETE):
            self.send_status(400)
            return

        length = self.headers.getheader('content-length')
        nbytes = int(length)
        data = self.rfile.read(nbytes)

        conn = model.db_connect(DBNAME)

        if url_data['command'] == POSTCREATE_GETALL:  # create
            self._create(conn, data)
        elif url_data['command'] == POSTUPDATE:  # update
            id = int(url_data['data'])
            self._update(conn, id, data)
        else:  # POSTDELETE - delete
            id = int(url_data['data'])  # the ID obtained from URL
            self._delete(conn, id)
Ejemplo n.º 6
0
    def confirm_email(token):
        email_id = s.loads(token, max_age=300)
        with model.db_connect() as connection:
            model.users.confirm_user(connection, email_id)
        flash('User {} is confirmed'.format(email_id))

        return flask.redirect(flask.url_for('index'))
Ejemplo n.º 7
0
def db_connection(database):
    """Connects to the database"""

    engine = db_connect(database)
    create_status_table(engine)
    Session = sessionmaker()
    Session.configure(bind=engine)

    return Session
Ejemplo n.º 8
0
def db_connection(database):
    """Connects to the database"""

    engine = db_connect(database)
    create_status_table(engine)
    Session = sessionmaker()
    Session.configure(bind=engine)

    return Session
Ejemplo n.º 9
0
 def do_DELETE(self):
     url_data = self.check_url()
     if not url_data:
         self.send_status(404)
         return
     if url_data['command'] != PATCH_DELETE_GET:
         self.send_status(400)
         return
     conn = model.db_connect(DBNAME)
     id = int(url_data['data'])  # the ID obtained from URL
     self._delete(conn, id)
Ejemplo n.º 10
0
    def stop(self):
        duration_sec = time.monotonic() - self.start_server_mono_time_sec

        # TODO: Add information about which user this is:
        session_data = {
            "start_datetime": self.start_server_date_time,
            "duration_sec": float(duration_sec),
            "game_id": str(self.game.id)
        }

        with model.db_connect() as model_db_connection:
            with contextlib.closing(model_db_connection.cursor()) as cursor:
                pass
Ejemplo n.º 11
0
    def do_PATCH(self):
        url_data = self.check_url()
        if not url_data:
            self.send_status(404)
            return

        if url_data['command'] != PATCH_DELETE_GET:
            self.send_status(400)
            return

        length = self.headers.getheader('content-length')
        nbytes = int(length)
        data = self.rfile.read(nbytes)

        conn = model.db_connect(DBNAME)

        id = int(url_data['data'])
        self._update(conn, id, data)
Ejemplo n.º 12
0
    def login_account():
        if flask.request.method == "GET":
            return flask.render_template("login-account.html")
        else:
            assert flask.request.method == "POST"
            form = flask.request.form

            email_id = form["email"]
            password = form["password"]

            with model.db_connect() as connection:
                success, msg = model.users.try_login_user(
                    connection, email_id, password)
                if success:
                    return flask.render_template_string(
                        "Success! Logged in {{ current_user.user_name }}.")
                else:
                    return flask.render_template("login-account.html",
                                                 errors=[msg])
Ejemplo n.º 13
0
def main():
    import argparse

    parser = argparse.ArgumentParser(
        description=
        """This is a Server that emulates behavior of the real Catalog Server."""
    )
    parser.add_argument(
        '--host',
        action='store',
        dest='host',
        default='localhost',
        help=
        '''Network address which the server should listen to. Default: localhost'''
    )
    parser.add_argument(
        '--port',
        action='store',
        dest='port',
        default=8080,
        type=int,
        help='''Network port which the server should listen to. Default: 8080'''
    )

    args = vars(parser.parse_args())

    server = BaseHTTPServer.HTTPServer
    handler = RequestHandler
    server_address = (args['host'], args['port'])
    print('INFO. Server is listening to %(host)s:%(port)s.' % args)

    conn = model.db_connect(DBNAME)
    if model.check_db_schema(conn):
        print('DB exists and tables created.')
    conn.close()

    srv = server(server_address, handler)
    try:
        srv.serve_forever()
    except KeyboardInterrupt:
        pass
    srv.server_close()
Ejemplo n.º 14
0
def url_visits(code):
	model.db_connect()
	url=model.url_info(code)
	model.db.close()
	return render_template("visits.html", url=url)
Ejemplo n.º 15
0
 def __init__(self):
     engine = db_connect()
     create_deals_table(engine)
     self.Session = sessionmaker(bind=engine)
Ejemplo n.º 16
0
def new_code():
	url = request.args.get("url")
	model.db_connect()
	code = model.create_code(url)
	model.db.close()
	return render_template("new_code.html", url=url, code=code)
Ejemplo n.º 17
0
def popular():
	model.db_connect()
	popular = model.most_popular()
	model.db.close()
	return render_template("popular.html", popular=popular)
Ejemplo n.º 18
0
 def __init__(self):
     engine = db_connect()
     create_myblog_table(engine)
     self.Session = sessionmaker(bind = engine)
Ejemplo n.º 19
0
def recent_urls():
	model.db_connect()
	recent = model.recently_shortened()
	model.db.close()
	return render_template("recent.html", recent=recent)