Skip to content

Commit

Permalink
example:cloudinary_image_upload
Browse files Browse the repository at this point in the history
  • Loading branch information
alesanchezr committed Oct 26, 2020
1 parent 74ea462 commit eec00d1
Show file tree
Hide file tree
Showing 9 changed files with 338 additions and 98 deletions.
3 changes: 3 additions & 0 deletions .gitpod.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@

image:
file: .gitpod.Dockerfile
ports:
- port: 3000
onOpen: open-preview
Expand Down
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ mysql-connector-python = "*"
flask-cors = "*"
gunicorn = "*"
mysqlclient = "*"
cloudinary = "*"

[requires]
python_version = "3.8"
Expand Down
209 changes: 125 additions & 84 deletions Pipfile.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
45 changes: 45 additions & 0 deletions migrations/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# A generic, single database configuration.

[alembic]
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false


# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
96 changes: 96 additions & 0 deletions migrations/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
from __future__ import with_statement

import logging
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from flask import current_app
config.set_main_option(
'sqlalchemy.url',
str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%'))
target_metadata = current_app.extensions['migrate'].db.metadata

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.


def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url, target_metadata=target_metadata, literal_binds=True
)

with context.begin_transaction():
context.run_migrations()


def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""

# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
logger.info('No changes in schema detected.')

connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool,
)

with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
process_revision_directives=process_revision_directives,
**current_app.extensions['migrate'].configure_args
)

with context.begin_transaction():
context.run_migrations()


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
24 changes: 24 additions & 0 deletions migrations/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}

"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}

# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}


def upgrade():
${upgrades if upgrades else "pass"}


def downgrade():
${downgrades if downgrades else "pass"}
21 changes: 10 additions & 11 deletions src/api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,15 @@

db = SQLAlchemy()

# class Person(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# username = db.Column(db.String(80), unique=True, nullable=False)
# email = db.Column(db.String(120), unique=True, nullable=False)
class UserImage(db.Model):
id = db.Column(db.Integer, primary_key=True)
url = db.Column(db.String(255), unique=True, nullable=False)

# def __repr__(self):
# return '<Person %r>' % self.username
def __repr__(self):
return '<Image %r>' % self.id

# def serialize(self):
# return {
# "username": self.username,
# "email": self.email
# }
def serialize(self):
return {
"url": self.url,
"id": self.id
}
36 changes: 33 additions & 3 deletions src/api/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
This module takes care of starting the API Server, Loading the DB and Adding the endpoints
"""
from flask import Flask, request, jsonify, url_for, Blueprint
from api.models import db
from api.utils import generate_sitemap
from api.models import db, UserImage
from api.utils import generate_sitemap, APIException
import cloudinary

#from models import Person

api = Blueprint('api', __name__)
Expand All @@ -16,4 +18,32 @@ def handle_hello():
"message": "Hello! I'm a message that came from the backend"
}

return jsonify(response_body), 200
return jsonify(response_body), 200

@api.route('/upload', methods=['POST', 'GET'])
def handle_upload():

if 'image' not in request.files:
raise APIException("No image to upload")

my_image = UserImage()

result = cloudinary.uploader.upload(
request.files['image'],
public_id=f'sample_folder/profile/my-image-name',
crop='limit',
width=450,
height=450,
eager=[{
'width': 200, 'height': 200,
'crop': 'thumb', 'gravity': 'face',
'radius': 100
},
],
tags=['profile_picture']
)

my_image.url = result['secure_url']
my_image.save()

return jsonify(my_image.serialize()), 200

0 comments on commit eec00d1

Please sign in to comment.