Skip to content

Commit

Permalink
Add all files
Browse files Browse the repository at this point in the history
  • Loading branch information
dongweiming committed Jun 12, 2016
1 parent 9831656 commit d83b795
Show file tree
Hide file tree
Showing 403 changed files with 46,525 additions and 0 deletions.
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
source /home/ubuntu/.virtualenvs/venv/bin/activate
28 changes: 28 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
FROM ubuntu:16.04

MAINTAINER DongWeiming <ciici123@gmail.com>
ENV DEBIAN_FRONTEND noninteractive

RUN echo 'deb http://mirrors.aliyun.com/ubuntu/ xenial main restricted universe multiverse\n\
deb http://mirrors.aliyun.com/ubuntu/ xenial-security main restricted universe multiverse\n\
deb http://mirrors.aliyun.com/ubuntu/ xenial-updates main restricted universe multiverse\n\
deb http://mirrors.aliyun.com/ubuntu/ xenial-proposed main restricted universe multiverse\n\
deb http://mirrors.aliyun.com/ubuntu/ xenial-backports main restricted universe multiverse\n\
deb-src http://mirrors.aliyun.com/ubuntu/ xenial main restricted universe multiverse\n\
deb-src http://mirrors.aliyun.com/ubuntu/ xenial-security main restricted universe multiverse\n\
deb-src http://mirrors.aliyun.com/ubuntu/ xenial-updates main restricted universe multiverse\n\
deb-src http://mirrors.aliyun.com/ubuntu/ xenial-proposed main restricted universe multiverse\n\
deb-src http://mirrors.aliyun.com/ubuntu/ xenial-backports main restricted universe multiverse\n\
' > /etc/apt/sources.list

RUN apt-get update
RUN apt-get install python curl git zsh sudo -yq
RUN useradd -ms /bin/bash ubuntu
RUN echo "ubuntu ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers
RUN echo "ubuntu:ubuntu" | chpasswd
USER ubuntu
workdir /home/ubuntu
RUN git clone https://github.com/dongweiming/web_develop
RUN cd /home/ubuntu/web_develop

EXPOSE 9000 3141 22 5000
12 changes: 12 additions & 0 deletions Vagrantfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# coding: utf-8
Vagrant.configure(2) do |config|
config.vm.box = "ubuntu/xenial64" # 设置box的名字
config.vm.hostname = "WEB"
# config.vm.synced_folder "/Users/dongweiming/web_develop", "/home/vagrant/web_develop"
config.vm.network :forwarded_port, guest: 9000, host: 9000
config.vm.network :forwarded_port, guest: 3141, host: 3141
config.vm.network :forwarded_port, guest: 5000, host: 5000
config.vm.provider "virtualbox" do |v|
v.customize ["modifyvm", :id, "--name", "web_dev", "--memory", "1536"]
end
end
Empty file added app.py
Empty file.
Empty file added chapter10/section2/__init__.py
Empty file.
134 changes: 134 additions & 0 deletions chapter10/section2/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
# coding=utf-8
import os

from werkzeug import SharedDataMiddleware
from flask import abort, Flask, request, jsonify, redirect, send_file

from ext import db, mako, render_template
from models import PasteFile
from utils import get_file_path, humanize_bytes
from client import create

ONE_MONTH = 60 * 60 * 24 * 30

app = Flask(__name__, template_folder='../../templates/r',
static_folder='../../static')
app.config.from_object('config')

app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
'/i/': get_file_path()
})

mako.init_app(app)
db.init_app(app)


@app.route('/r/<img_hash>')
def rsize(img_hash):
w = request.args['w']
h = request.args['h']

old_paste = PasteFile.get_by_filehash(img_hash)
new_paste = PasteFile.rsize(old_paste, w, h)

return new_paste.url_i


@app.route('/d/<filehash>', methods=['GET'])
def download(filehash):
paste_file = PasteFile.get_by_filehash(filehash)

return send_file(open(paste_file.path, 'rb'),
mimetype='application/octet-stream',
cache_timeout=ONE_MONTH,
as_attachment=True,
attachment_filename=paste_file.filename.encode('utf-8'))


@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
uploaded_file = request.files['file']
w = request.form.get('w')
h = request.form.get('h')
if not uploaded_file:
return abort(400)

rs = create(uploaded_file, width=w, height=h)
if rs['r']:
return rs['error']

paste_file = rs['paste_file']

return jsonify({
'url_d': paste_file.url_d % request.host,
'url_i': paste_file.url_i % request.host,
'url_s': paste_file.url_s % request.host,
'url_p': paste_file.url_p % request.host,
'filename': paste_file.filename,
'size': humanize_bytes(paste_file.size),
'uploadtime': paste_file.uploadtime,
'type': paste_file.type,
'quoteurl': paste_file.quoteurl.replace('%25s', request.host)
})

return render_template('index.html', **locals())


@app.after_request
def after_request(response):
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
return response


@app.route('/j', methods=['POST'])
def j():
uploaded_file = request.files['file']

if uploaded_file:
rs = create(uploaded_file)
if rs['r']:
return rs['error']

paste_file = rs['paste_file']

width, height = paste_file.image_size

return jsonify({
'url': paste_file.url_i,
'short_url': paste_file.url_s,
'origin_filename': paste_file.filename,
'hash': paste_file.filehash,
'width': width,
'height': height
})

return abort(400)


@app.route('/p/<filehash>')
def preview(filehash):
paste_file = PasteFile.get_by_filehash(filehash)

if not paste_file:
filepath = get_file_path(filehash)
if not(os.path.exists(filepath) and (not os.path.islink(filepath))):
return abort(404)

paste_file = PasteFile.create_by_old_paste(filehash)
db.session.add(paste_file)
db.session.commit()

return render_template('success.html', p=paste_file)


@app.route('/s/<symlink>')
def s(symlink):
paste_file = PasteFile.get_by_symlink(symlink)

return redirect(paste_file.url_p)


if __name__ == '__main__':
app.run(host='0.0.0.0', port=9000)
3 changes: 3 additions & 0 deletions chapter10/section2/calc.thrift
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
service CalcService {
i64 add(1:i64 a, 2:i64 b),
}
56 changes: 56 additions & 0 deletions chapter10/section2/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# coding=utf-8
import sys

sys.path.append('gen-py')
sys.path.insert(0, '/usr/lib/python2.7/site-packages')

from thrift.transport import TTransport, TSocket
from thrift.protocol import TBinaryProtocol

from pastefile import PasteFileService
from pastefile.ttypes import (
PasteFile, CreatePasteFileRequest, UploadImageError,
NotFound)

from werkzeug.local import LocalProxy


def get_client():
transport = TSocket.TSocket('localhost', 8200)
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = PasteFileService.Client(protocol)
transport.open()
return client

client = LocalProxy(get_client)


def create(uploaded_file, width=None, height=None):
filename = uploaded_file.filename.encode('utf-8')
mimetype = uploaded_file.mimetype.encode('utf-8')
filehash, path = client.get_file_info(filename, mimetype)

create_request = CreatePasteFileRequest()

create_request.filename = filename
create_request.mimetype = mimetype
create_request.filehash = filehash

uploaded_file.save(path)
if width is not None and height is not None:
create_request.width = width
create_request.height = height
try:
pastefile = client.create(create_request)
except UploadImageError:
return {'r': 1, 'error': 'upload fail'}

print isinstance(pastefile, PasteFile)

try:
paste_file = client.get(pastefile.id)
except NotFound:
return {'r': 1, 'error': 'not found'}

return {'r': 0, 'paste_file': paste_file}
21 changes: 21 additions & 0 deletions chapter10/section2/client_with_thriftpy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# coding=utf-8
import os

import thriftpy
from thriftpy.rpc import client_context
from thriftpy.protocol import TBinaryProtocolFactory
from thriftpy.transport import TBufferedTransportFactory

HERE = os.path.abspath(os.path.dirname(__file__))

calc_thrift = thriftpy.load(
os.path.join(HERE, 'calc.thrift'),
module_name='calc_thrift')

with client_context(calc_thrift.CalcService,
'127.0.0.1', 8300,
proto_factory=TBinaryProtocolFactory(),
trans_factory=TBufferedTransportFactory(),
timeout=None) as calc:
rs = calc.add(1, 2)
print 'Result is: {}'.format(rs)
5 changes: 5 additions & 0 deletions chapter10/section2/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# coding=utf-8
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'mysql://web:web@localhost:3306/r'
UPLOAD_FOLDER = '/tmp/permdir'
SQLALCHEMY_TRACK_MODIFICATIONS = False
6 changes: 6 additions & 0 deletions chapter10/section2/ext.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# coding=utf-8
from flask_mako import MakoTemplates, render_template # noqa
from flask_sqlalchemy import SQLAlchemy

mako = MakoTemplates()
db = SQLAlchemy()
Empty file.
108 changes: 108 additions & 0 deletions chapter10/section2/gen-py/pastefile/PasteFileService-remote
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
#!/usr/bin/env python
#
# Autogenerated by Thrift Compiler (0.9.3)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#

import sys
import pprint
from urlparse import urlparse
from thrift.transport import TTransport
from thrift.transport import TSocket
from thrift.transport import TSSLSocket
from thrift.transport import THttpClient
from thrift.protocol import TBinaryProtocol

from pastefile import PasteFileService
from pastefile.ttypes import *

if len(sys.argv) <= 1 or sys.argv[1] == '--help':
print('')
print('Usage: ' + sys.argv[0] + ' [-h host[:port]] [-u url] [-f[ramed]] [-s[sl]] function [arg1 [arg2...]]')
print('')
print('Functions:')
print(' PasteFile get(i32 pid)')
print(' get_file_info(string filename, string mimetype)')
print(' PasteFile create(CreatePasteFileRequest request)')
print('')
sys.exit(0)

pp = pprint.PrettyPrinter(indent = 2)
host = 'localhost'
port = 9090
uri = ''
framed = False
ssl = False
http = False
argi = 1

if sys.argv[argi] == '-h':
parts = sys.argv[argi+1].split(':')
host = parts[0]
if len(parts) > 1:
port = int(parts[1])
argi += 2

if sys.argv[argi] == '-u':
url = urlparse(sys.argv[argi+1])
parts = url[1].split(':')
host = parts[0]
if len(parts) > 1:
port = int(parts[1])
else:
port = 80
uri = url[2]
if url[4]:
uri += '?%s' % url[4]
http = True
argi += 2

if sys.argv[argi] == '-f' or sys.argv[argi] == '-framed':
framed = True
argi += 1

if sys.argv[argi] == '-s' or sys.argv[argi] == '-ssl':
ssl = True
argi += 1

cmd = sys.argv[argi]
args = sys.argv[argi+1:]

if http:
transport = THttpClient.THttpClient(host, port, uri)
else:
socket = TSSLSocket.TSSLSocket(host, port, validate=False) if ssl else TSocket.TSocket(host, port)
if framed:
transport = TTransport.TFramedTransport(socket)
else:
transport = TTransport.TBufferedTransport(socket)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = PasteFileService.Client(protocol)
transport.open()

if cmd == 'get':
if len(args) != 1:
print('get requires 1 args')
sys.exit(1)
pp.pprint(client.get(eval(args[0]),))

elif cmd == 'get_file_info':
if len(args) != 2:
print('get_file_info requires 2 args')
sys.exit(1)
pp.pprint(client.get_file_info(args[0],args[1],))

elif cmd == 'create':
if len(args) != 1:
print('create requires 1 args')
sys.exit(1)
pp.pprint(client.create(eval(args[0]),))

else:
print('Unrecognized method %s' % cmd)
sys.exit(1)

transport.close()
Loading

0 comments on commit d83b795

Please sign in to comment.