Commit 2796a453 authored by Roman Shishkin's avatar Roman Shishkin

Работающая загрузка файлов и сохранение их в базу

parent 30a99e8c
......@@ -12,10 +12,20 @@ class Post(db.Entity):
summary = orm.Required(str)
details = orm.Optional(str)
source = orm.Optional(str)
photo = orm.Optional(str)
video = orm.Optional(str)
latitude = orm.Required(float)
longitude = orm.Required(float)
author = orm.Required(int)
photos = orm.Set("Photo")
author = orm.Required("User")
state = orm.Required(str, sql_default='pending')
timestamp = orm.Required(datetime, sql_default='CURRENT_TIMESTAMP')
\ No newline at end of file
timestamp = orm.Required(datetime, sql_default='CURRENT_TIMESTAMP')
class Photo(db.Entity):
user = orm.Required("User")
url = orm.Required(str)
post = orm.Optional("Post")
latitude = orm.Optional(float)
longitude = orm.Optional(float)
timestamp = orm.Required(datetime, sql_default='CURRENT_TIMESTAMP')
class User(db.Entity):
vk_id = orm.Required(int, unique=True)
photos = orm.Set("Photo")
posts = orm.Set("Post")
import os
import hashlib
from pony import orm
from .models import User
def get_static_hash():
if os.path.exists('frontend.ver'):
......@@ -14,4 +15,11 @@ def get_static_hash():
def check_user(app_id, viewer_id, app_secret, hash):
m = hashlib.md5('{}_{}_{}'.format(str(app_id), str(viewer_id), app_secret).encode())
return m.hexdigest().lower() == hash
\ No newline at end of file
return m.hexdigest().lower() == hash
@orm.db_session
def get_user_from_db(vk_id):
user = User.get(vk_id=vk_id)
if user is None:
user = User(vk_id=vk_id)
return user
from flask import render_template, request, redirect, url_for
from ..utils import check_user
from ..utils import check_user, get_user_from_db
from pony import orm
def init(app):
@app.route('/')
......@@ -11,12 +12,14 @@ def init(app):
if viewer_id is None or viewer_type is None or group_id is None or auth_key is None or check_user(app.config['APP_ID'], viewer_id, app.config['APP_SECRET'], auth_key) is False:
return render_template('error.html')
if viewer_type == '4':
get_user_from_db(viewer_id)
if viewer_type == '4': # Admin
return redirect(url_for('admin', _scheme='https', _external=True, id=viewer_id, key=auth_key))
elif viewer_type == '3':
return redirect(url_for('admin', _scheme='editor', _external=True, id=viewer_id, key=auth_key))
elif viewer_type == '3': # Editor
return redirect(url_for('editor', _scheme='https', _external=True, id=viewer_id, key=auth_key))
else:
return redirect(url_for('admin', _scheme='submit', _external=True, id=viewer_id, key=auth_key))
return redirect(url_for('submit', _scheme='https', _external=True, id=viewer_id, key=auth_key))
@app.route('/submit/<int:id>/<string:key>')
def submit(id, key):
......
from flask import render_template, request
from ..utils import check_user
from ..utils import check_user, get_user_from_db
import json
from flask_uploads import configure_uploads, UploadSet, IMAGES
import uuid
from ..models import User, Photo
from pony import orm
from flask_uploads import configure_uploads, UploadSet, UploadNotAllowed, IMAGES
def init(app):
photos = UploadSet('photos', IMAGES)
......@@ -13,6 +16,14 @@ def init(app):
return render_template('error.html')
if request.method == 'POST' and 'file' in request.files:
filename = photos.save(request.files['file'])
return json.dumps({'filename':photos.url(filename)})
try:
filename = photos.save(request.files['file'], name='{}.'.format(uuid.uuid4()))
with orm.db_session:
user = get_user_from_db(id)
# TODO(spark): parse exif for location
photo = Photo(url=photos.url(filename), user=user)
orm.commit()
return json.dumps({'id': photo.id,'filename': photos.url(filename)})
except UploadNotAllowed:
return json.dumps({'error':True})
return json.dumps({'error':True})
\ No newline at end of file
class PhotosUploadController {
constructor($scope, FileUploader) {
constructor($scope, FileUploader, $uibModal) {
$scope.uploader = new FileUploader();
$scope.uploader.url = '/upload/'+user_id+'/'+user_key;
$scope.uploader.autoUpload = true;
$scope.files = []; // List of urls
$scope.uploader.onSuccessItem = (item, response, status, headers) => {
if(typeof response.error === "undefined") {
// Successful upload
$scope.files.push(response);
} else {
alert("Произошла ошибка при загрузке файла");
}
};
let input = document.getElementById('file_upload');
$scope.addPhoto = () => {
input.click();
}
};
}
}
PhotosUploadController.$inject = ['$scope', 'FileUploader'];
PhotosUploadController.$inject = ['$scope', 'FileUploader', '$uibModal'];
export default PhotosUploadController;
\ No newline at end of file
......@@ -76,17 +76,18 @@
</script>
<div class="row">
<div class="col-md-3" ng-controller="PhotosUploadController">
<a class="btn btn-success" ng-click="addPhoto()"><span class="glyphicon glyphicon-paperclip"></span></a>
<div class="col-md-7" ng-controller="PhotosUploadController">
<input type="file" id="file_upload" nv-file-select uploader="uploader" style="display: none"/>
<ul>
<li ng-repeat="item in uploader.queue">
Name: <span ng-bind="item.file.name"></span><br/>
<button ng-click="item.upload()">upload</button>
</li>
</ul>
<div class="image-list">
<div class="image-list__btn">
<a class="btn btn-success" ng-click="addPhoto()"><span class="glyphicon glyphicon-paperclip"></span></a>
</div>
<div ng-repeat="file in files" class="image-list__container">
<img src="{{file.filename}}" class="image-list__image thumbnail">
</div>
</div>
</div>
<div class="col-md-6">
<div class="col-md-2">
<div class="charNum-container"><label id="charNum"> </label></div>
</div>
<div class="col-md-3">
......
......@@ -17,4 +17,20 @@ textarea {
.charNum-container{
display: inline-block;
}
.image-list {
}
.image-list__container {
display: inline-block;
}
.image-list__image {
max-height: 64px;
display: inline-block;
}
.image-list__btn, .image-list__btn:hover {
vertical-align: top;
margin: 15px;
display: inline-block;
}
\ No newline at end of file
......@@ -14,6 +14,12 @@ volumes:
mode: 0o700
user: 1
group: 1
/uploads: !Persistent
path: /storage/uploads
mkdir: true
mode: 0o700
user: 1
group: 1
workdir: /app
stdout-stderr-file: /storage/std.log
environ:
......
......@@ -85,6 +85,7 @@ containers:
- *host_resolution
- !EnsureDir /app
- !EnsureDir /storage
- !EnsureDir /uploads
- !Copy
source: /work
path: /app
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment