|
1 | 1 | import logging |
2 | 2 | from contextlib import contextmanager |
| 3 | +from io import BytesIO |
3 | 4 | from time import sleep |
4 | 5 | from typing import Union |
5 | 6 |
|
| 7 | +import boto3 |
6 | 8 | import psycopg2 |
7 | | -from sqlalchemy import create_engine, update |
| 9 | +import requests |
| 10 | +from sqlalchemy import create_engine, select, update |
| 11 | +from sqlalchemy.sql import functions |
8 | 12 |
|
9 | | -from .models import Base, sa_companies |
| 13 | +from .models import Base, sa_companies, sa_contractors |
10 | 14 | from .settings import Settings |
11 | 15 |
|
12 | 16 | logger = logging.getLogger('socket') |
@@ -260,3 +264,39 @@ def run_sql_prepare(conn): |
260 | 264 | run SQL_PREPARE code to (re)create procedures and triggers |
261 | 265 | """ |
262 | 266 | conn.execute(SQL_PREPARE) |
| 267 | + |
| 268 | + |
| 269 | +@patch |
| 270 | +def update_socket_images(conn): |
| 271 | + """ |
| 272 | + Downloading images from server on EC2 and uploading them to S3 |
| 273 | + """ |
| 274 | + con_c = sa_contractors.c |
| 275 | + company_c = sa_companies.c |
| 276 | + base_url = 'https://socket.tutorcruncher.com/media' |
| 277 | + q_iter = select([con_c.id, company_c.public_key]).select_from(sa_contractors.join(sa_companies)) |
| 278 | + session = requests.Session() |
| 279 | + settings = Settings() |
| 280 | + s3_client = boto3.client( |
| 281 | + 's3', aws_access_key_id=settings.aws_access_key, aws_secret_access_key=settings.aws_secret_key |
| 282 | + ) |
| 283 | + count = conn.execute(select([functions.count(con_c.id)]).select_from(sa_contractors)) |
| 284 | + print(f'Processing images for {count.first()[0]} contractors') |
| 285 | + for row in conn.execute(q_iter): |
| 286 | + img_key = f'{row.public_key}/{row.id}.jpg' |
| 287 | + r = session.get(f'{base_url}/{img_key}') |
| 288 | + r.raise_for_status() |
| 289 | + with BytesIO() as temp_file: |
| 290 | + temp_file.write(r.content) |
| 291 | + temp_file.seek(0) |
| 292 | + s3_client.upload_fileobj(Fileobj=temp_file, Bucket=settings.aws_bucket_name, Key=img_key) |
| 293 | + print(f'Uploading image {img_key}') |
| 294 | + |
| 295 | + img_thumb_key = f'{row.public_key}/{row.id}.thumb.jpg' |
| 296 | + r = session.get(f'{base_url}/{img_thumb_key}') |
| 297 | + r.raise_for_status() |
| 298 | + with BytesIO() as temp_file: |
| 299 | + temp_file.write(r.content) |
| 300 | + temp_file.seek(0) |
| 301 | + s3_client.upload_fileobj(Fileobj=temp_file, Bucket=settings.aws_bucket_name, Key=img_thumb_key) |
| 302 | + print(f'Uploading image {img_thumb_key}') |
0 commit comments