Skip to content

Instantly share code, notes, and snippets.

@dengshuan
Created May 13, 2014 11:18
Show Gist options
  • Save dengshuan/c4d783380f38d6a510b2 to your computer and use it in GitHub Desktop.
Save dengshuan/c4d783380f38d6a510b2 to your computer and use it in GitHub Desktop.
Upload pictures to qiniu within a flask app
from flask import Flask, jsonify, request, redirect, url_for, render_template
from flask.ext.sqlalchemy import SQLAlchemy
from datetime import datetime
import qiniu.conf, qiniu.rs
import os
app = Flask(__name__)
app.config['DATABASE_FILE'] = 'app.db'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DATABASE_FILE']
app.config['AK'] = 'YOUR QINIU ACCESS KEY'
app.config['SK'] = 'YOUR QINIU SECRET KEY'
app.config['BUCKET'] = 'YOUR QINIU BUCKET'
qiniu.conf.ACCESS_KEY = app.config['AK']
qiniu.conf.SECRET_KEY = app.config['SK']
db = SQLAlchemy(app)
class Picture(db.Model):
__tablename__ = 'picture'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50))
description = db.Column(db.Text)
key = db.Column(db.String(200))
timestamp = db.Column(db.DateTime)
def __repr__(self):
return '<Picture %r' % (self.title)
@app.route('/')
def index():
pictures = Picture.query.order_by('timestamp desc').all()
policy = qiniu.rs.PutPolicy(app.config['BUCKET'])
policy.callbackUrl = 'http://YOUR-SERVER:8000/upload'
policy.callbackBody = 'key=$(key)&title=$(x:title)&description=$(x:description)'
uptoken = policy.token()
timestamp = datetime.now()
return render_template('index.html', token=uptoken, pictures=pictures)
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
title = request.form['title']
key = request.form['key']
description = request.form['description']
timestamp = datetime.now()
picture = Picture(title=title, key=key, description=description, timestamp=timestamp)
db.session.add(picture)
db.session.commit()
return jsonify(title=title, description=description, timestamp=timestamp, key=key)
else:
return redirect(url_for('index'))
if __name__ == '__main__':
app_dir = os.path.realpath(os.path.dirname(__file__))
database_path = os.path.join(app_dir, app.config['DATABASE_FILE'])
if not os.path.exists(database_path):
db.create_all()
app.run(debug=True, host='0.0.0.0', port=8000)
<!doctype html>
<html>
<head>
<title>Flask Qiniu Demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function(){
var options = {
success: showResponse,
clearForm: true
};
$("#myForm").submit(function(){
$(this).ajaxSubmit(options);
return false;
});
function showResponse(responseText, statusText, xhr, $form){
$("#pictures").prepend('<img src="http://YOUR-BUCKET.qiniudn.com/' + responseText.key + '" alt="' + responseText.title + '" title="' + responseText.description +'"/><br/>Uploaded at ' + responseText.timestamp + '<br/>');
};
});
</script>
</head>
<body>
<h1>A demo to upload picture to qiniu within a Flask app</h1>
<form id="myForm" method="post" action="http://up.qiniu.com" enctype="multipart/form-data">
<input type="hidden" name="token" value="{{ token }}" />
<input type="file" name="file" value="" />
<input type="text" name="x:title" value="" placeholder="title" />
<input type="text" name="x:description" value="" placeholder="description"/>
<input type="submit" name="submit" value="Upload" />
</form>
<p>Picture uploaded successfully will be shown below:</p>
<div id="pictures" class="galleries">
{% for picture in pictures %}
<img src="http://YOUR-BUCKET.qiniudn.com/{{ picture.key }}" alt="{{ picture.title }}" title="{{ picture.description }}"/><br />Uploaded at {{ picture.timestamp }}<br/>
{% endfor %}
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment