Skip to content

Instantly share code, notes, and snippets.

@arischow
Last active March 22, 2017 02:48
Show Gist options
  • Save arischow/6e81d44497aa688418b6e6ce36d211cf to your computer and use it in GitHub Desktop.
Save arischow/6e81d44497aa688418b6e6ce36d211cf to your computer and use it in GitHub Desktop.
Flask
# Check http://stackoverflow.com/questions/17285826/flask-redirecting-multiple-routes for more details.
from flask import Flask
app = Flask(__name__)
app.config['SERVER_NAME'] = 'aris.local:5000'
@app.route('/')
def helloworld():
return 'Hello World!'
@app.route('/', subdomain='fuck')
def shit():
return 'Hello JavaShit!'
if __name__ == '__main__':
app.run(debug=True)
# Before opening it, you should edit your hosts file as follows:
# 127.0.0.1 aris.local
# 127.0.0.1 fuck.aris.local
# Now you can open http://aris.local:5000 and http://fuck.aris.local:5000 to get the results
import os
from flask import Flask
from flask import request
from flask import flash
from flask import redirect
from flask import url_for
from werkzeug.utils import secure_filename
FILE_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) # .py 文件的所在目录
UPLOAD_FOLDER = FILE_DIRECTORY + '/static/uploads' # 请在 static 内创建 uploads 文件夹,否则会报错
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif']) # 仅限图片
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# print('request.files:', request.files) # ImmutableMultiDict
# print('request.files['file']:', file) # FileStorage Class
# print('request.files['file'].filename:', file.filename) # str
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file',
filename=filename))
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File (Image Only)</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
@app.route('/success')
def uploaded_file():
filename = request.args.get('filename')
print(filename)
# return render_template('succeeded.html', filename=filename)
return '''
<h1>You have successfully uploaded your file.</h1>
<img src="/static/uploads/{}">
'''.format(filename)
if __name__ == '__main__':
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment