Created
November 16, 2020 20:22
-
-
Save saippuakauppias/0faeea9ee0fcf568e671ca32ecdd865b to your computer and use it in GitHub Desktop.
Code Review Test Case
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
$ pip install flask sqlalchemy psycopg2-binary | |
$ FLASK_ENV=development FLASK_APP=app.py flask run | |
""" | |
import random | |
from flask import Flask, abort, request, views | |
from sqlalchemy import Column, MetaData, String, Table, create_engine, select | |
from string import ascii_letters | |
from typing import Optional | |
engine = create_engine('postgresql://sks@localhost/postgres') | |
meta = MetaData(engine) | |
urls = Table('urls', meta, | |
Column('full_url', String), | |
Column('short_url', String, unique=True) | |
) | |
meta.create_all() | |
class URLView(views.MethodView): | |
def get(self, short_url: Optional[str]): | |
global engine | |
stmt = select(meta.tables.values()).where(urls.c.short_url == short_url) | |
conn = engine.connect() | |
result = conn.execute(stmt).fetchone() | |
if not result: | |
return { | |
'error': 'Not found' | |
} | |
return { | |
'full_url': result.full_url | |
} | |
def post(self): | |
global engine | |
full_url = request.form.get('full_url') | |
if not full_url: | |
return abort(400, 'Missed required param: full_url') | |
short_url = ''.join(random.sample(ascii_letters, 6)) | |
conn = engine.connect() | |
result = conn.execute(f"INSERT INTO urls VALUES ('{short_url}', '{full_url}')") | |
conn.commit() | |
return { | |
'short_url': short_url | |
} | |
app = Flask(__name__) | |
api_url_view = URLView.as_view('api_url') | |
app.add_url_rule('/<short_url>', view_func=api_url_view, methods=['GET']) | |
app.add_url_rule('/add', view_func=api_url_view, methods=['POST']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment