尝试使用flask-security启用登录烧瓶.以下代码工作正常(我导入__init__.py)
from flask import Blueprint, render_template, request, redirect, url_for
from coursly import app
from coursly.models import *
from flask.ext.security import Security, LoginForm, SQLAlchemyUserDatastore
user_datastore = SQLAlchemyUserDatastore(db, user.User, user.Role)
Security(app, user_datastore)
user = Blueprint('user', __name__)
@user.route('/')
def index():
return redirect(url_for("user.login"))
@user.route('/login', methods=['GET', 'POST'])
def login():
return render_template('user/login.html', content='Login Page', action=url_for('auth.authenticate'), form=LoginForm())
Run Code Online (Sandbox Code Playgroud)
但是,如果我改变user = Blueprint('user', __name__)对user = Blueprint('user', __name__, url_prefix='/blah')失败了werkzeug.routing.BuildError BuildError: ('auth.authenticate', {}, None).url_for是问题,但是,我不明白为什么.HALP!
我遇到了Flask视图的问题,该视图应该返回内容类型为"application/json"的响应以响应POST请求.具体来说,如果我这样做:
curl -v -d 'foo=bar' http://example.org/jsonpost
Run Code Online (Sandbox Code Playgroud)
对此观点:
@app.route('/jsonpost', methods=['GET', 'POST'])
def json_post():
resp = make_response('{"test": "ok"}')
resp.headers['Content-Type'] = "application/json"
return resp
Run Code Online (Sandbox Code Playgroud)
我得到某种连接重置:
* About to connect() to example.org port 80 (#0)
* Trying xxx.xxx.xxx.xxx... connected
* Connected to example.org (xxx.xxx.xxx.xxx) port 80 (#0)
> POST /routing/jsonpost HTTP/1.1
> User-Agent: curl/7.19.7 (i486-pc-linux-gnu) libcurl/7.19.7 OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15
> Host: example.org
> Accept: */*
> Content-Length: 7
> Content-Type: application/x-www-form-urlencoded
>
< HTTP/1.1 200 OK
< Server: nginx/1.2.4
< Date: Thu, 27 Dec …Run Code Online (Sandbox Code Playgroud) 我问,因为我想知道我是否可以使用文本文件作为简单应用程序的数据存储.如果每个处理程序运行完成,那么看起来我应该能够在该请求期间修改文本文件而不用担心冲突,假设我在每个请求结束时关闭文件.
这可行吗?为了在Flask应用程序中将文本文件用作数据存储,我需要做些什么特别的事情吗?
我有一个烧瓶应用程序,我做了一堆所有关系相互关联的类:
用户课程讲义笔记队列资产
所以我正在尝试做一个新的讲座和笔记,我为每件事都定义了一个方法.
def createPad(user,course,lecture):
lecture.queues.first().users.append(user)
# make new etherpad for user to wait in
newNote = Note(dt) # init also creates a new pad at /p/groupID$noteID
db.session.add(newNote)
#db.session.commit()
# add note to user, course, and lecture
user.notes.append(newNote)
course.notes.append(newNote)
lecture.notes.append(newNote)
db.session.commit()
return newNote
Run Code Online (Sandbox Code Playgroud)
def createLecture(user, course):
# create new lecture
now = datetime.now()
dt = now.strftime("%Y-%m-%d-%H-%M")
newLecture = Lecture(dt)
db.session.add(newLecture)
# add lecture to course, add new queue to lecture, add user to queue, add new user to …Run Code Online (Sandbox Code Playgroud) 我在一个名为css的文件夹中有一个文件test.css.我想为这个文件创建url.我知道,我可以使用url_for像
url_for('static', filename="test.css")
Run Code Online (Sandbox Code Playgroud)
创建网址,static/test.css但我不能使用像
url_for('css', filename="test.css")
Run Code Online (Sandbox Code Playgroud)
创建我感兴趣的网址 css/test.css
我怎样才能做到这一点?
我正在尝试按照以下教程 http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world#commentform
我好像很迷茫.首先从我的理解.运行命令'python virtualenv.py flask'在文件夹'flask'中创建一个虚拟python环境.它是否正确?
第二,这是不是意味着如果我cd到这个文件夹然后运行'pip install flask'它应该将flask安装到该文件夹?当我运行任何这些pip安装命令时,我的终端充满了疯狂的疯狂,我不明白.
Benjamins-MacBook:flask test$ pip install flask==0.9
Downloading/unpacking flask==0.9
Downloading Flask-0.9.tar.gz (481kB): 481kB downloaded
Running setup.py egg_info for package flask
warning: no files found matching '*' under directory 'tests'
warning: no previously-included files matching '*.pyc' found under directory 'docs'
warning: no previously-included files matching '*.pyo' found under directory 'docs'
warning: no previously-included files matching '*.pyc' found under directory 'tests'
warning: no previously-included files matching '*.pyo' found under directory 'tests'
warning: no previously-included files matching …Run Code Online (Sandbox Code Playgroud) 我知道如何处理烧瓶"在应用程序环境之外工作"的问题很少,但我无法让它为我工作
我有一个长期运行的mongo聚合查询,并计划使用apscheduler定期运行.下面是我的应用程序结构,但任务失败,出现"RuntimeError:在应用程序上下文之外工作".ihttp://flask.pocoo.org/docs/patterns/sqlite3/有一些关于使用新flask.g的例子,但想知道是否有人可以建议如何全局正确保存mongodb连接并在apscheduler中共享该连接
__init.py__
from app import create_app
Run Code Online (Sandbox Code Playgroud)
app.py
from flask import Flask, request, render_template,g
from .extention import mongo, redis, sched
def create_app(config=None):
"""Create a Flask app."""
app = Flask(__name__)
configure_extensions(app)
return app
def configure_extensions(app):
mongo.init_app(app) # initialise mongo connection from the config
redis.init_app(app)
from schedule_tasks import *
Run Code Online (Sandbox Code Playgroud)
extention.py
from flask.ext.pymongo import PyMongo
mongo = PyMongo()
from apscheduler.scheduler import Scheduler
config = {'apscheduler.jobstores.file.class': 'apscheduler.jobstores.shelve_store:ShelveJobStore',
'apscheduler.jobstores.file.path': '/tmp/sched_dbfile'}
sched = Scheduler(config)
from flask.ext.redis import Redis
redis = Redis()
Run Code Online (Sandbox Code Playgroud)
schedule_tasks.py
from .extention import mongo …Run Code Online (Sandbox Code Playgroud) 似乎python(2.6)无法优化这个简单的临时变量'a'?
我用来为一些代码分配一个局部变量,以减少行长度.
对我来说,这是一个简单的优化任何正确的编译器可以自动执行
from dis import dis
def f(func):
func()
def functioncall():
print ' => function called'
def unoptimized():
print 'in unoptimized'
a = functioncall
f(func=a)
def optimized():
print 'in optimized'
f(func=functioncall)
unoptimized()
optimized()
print 'dis(unoptimized)'
dis(unoptimized)
print 'dis(optimized)'
dis(optimized)
Run Code Online (Sandbox Code Playgroud)
输出:
in unoptimized
=> function called
in optimized
=> function called
dis(unoptimized)
10 0 LOAD_CONST 1 ('in unoptimized')
3 PRINT_ITEM
4 PRINT_NEWLINE
11 5 LOAD_GLOBAL 0 (functioncall)
8 STORE_FAST 0 (a)
12 11 LOAD_GLOBAL 1 (f)
14 LOAD_CONST 2 ('func') …Run Code Online (Sandbox Code Playgroud) 我想知道是否有人使用这个烧瓶扩展来简化http-basic-auth.
基本上我不明白这个例子:
users = {
"john": "hello",
"susan": "bye"
}
@auth.get_password
def get_pw(username):
if username in users:
return users[username]
return None
Run Code Online (Sandbox Code Playgroud)
该get_password装饰好像返回给用户的清除密码,如果它给用户提供了一个相匹配,则授权将被授予.
但是,没有人应该首先访问用户的明确密码.我通常会将明确的密码和用户名发送到后端,散列密码并将其与数据库中现有的哈希密码进行比较.
这是如何设想的?
更新:
与文档的链接更加轻松.因为有第二个装饰器需要实现这个:
@auth.hash_password
def hash_pw(username, password):
get_salt(username)
return hash(password, salt)
Run Code Online (Sandbox Code Playgroud)
字面上的规则是 get_password(username) == hash_password(password)
我理解这一点的方法是get_password在数据库中返回用户的哈希密码,该密码需要等于hash_password方法中定义的当前哈希密码.
问题是,我使用的是passlib中的sha256_crypt.
def verify_password(password, hashed_password_in_db, password_hash_version):
if password_hash_version == 1:
return sha256_crypt.verify(password, hashed_password_in_db)
return False
Run Code Online (Sandbox Code Playgroud)
在这里,您不能散列给定的密码并将其与存储的散列密码进行比较.我必须使用sha256_crypt.verify(password, hashed_password_in_db)返回false或true的方法.
有没有办法实现这一点,还是我必须推出自己的自定义解决方案?谢谢
我正在尝试创建接收请求的上传网站,并将文件存储在烧瓶中的"静态"文件夹中.当我尝试发送"POST"请求时,我总是得到错误的请求.我需要它的唯一原因是测试我的拖放javascript上传器.有人能指出我正确的方向吗?
import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename
UPLOAD_FOLDER = 'static'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', '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':
file = request.files['xhr2upload'] # [0]
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</h1>
<form …Run Code Online (Sandbox Code Playgroud) python ×10
flask ×9
database ×1
http-headers ×1
json ×1
mongodb ×1
pip ×1
post ×1
pymongo ×1
python-2.6 ×1
sqlalchemy ×1
url-for ×1
virtualenv ×1