小编use*_*663的帖子

如何使用SQLAlchemy只选择一列?

我想仅使用"where子句"从我的数据库中选择(并返回)一个字段.代码是:

from sqlalchemy.orm import load_only
    @application.route("/user", methods=['GET', 'POST'])
    def user():
        user_id = session.query(User, User.validation==request.cookies.get("validation")).options(load_only("id"))
        session.commit()
        return user_id
Run Code Online (Sandbox Code Playgroud)

这失败了,回溯是:

File "/Library/Python/2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Python/2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1478, in full_dispatch_request
response = self.make_response(rv)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1577, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/Library/Python/2.7/site-packages/werkzeug/wrappers.py", line 841, in force_type
response …
Run Code Online (Sandbox Code Playgroud)

python sqlalchemy flask

15
推荐指数
4
解决办法
4万
查看次数

使用Flask,python和postgresql如何连接到预先存在的数据库?

我想连接到一个预先存在的postgres数据库,该数据库在我的应用程序中没有与之关联的模型.也许不出所料,这是一个麻烦的补充,这是我第一次使用Python和Flask.

app/py代码是:

import os
from flask import Flask
from flask import render_template
from flask.ext.sqlalchemy import SQLAlchemy  
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://blah:blah@ec2-54-227-254-13.compute-1.amazonaws.com:5432/mydb'
db = SQLAlchemy(app)
db.create_all()
db.session.commit()

@app.route("/")
def main():
    return render_template('index.html')


@app.route('/base')
def base():
    myusers = users.all()
    return render_template('base.html')

if __name__ == '__main__':
    app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)

def main()的工作原理使我取得了很多成就.

在视图(base.html)中我们有:

{% for user in myusers %}
    <div><p>{{ user.first_name }} </b></p></div>
    {% endfor %}
Run Code Online (Sandbox Code Playgroud)

当我转到base.html页面时,持久性错误是 NameError: global name 'users' is not defined …

python postgresql flask

8
推荐指数
1
解决办法
3772
查看次数

使用Python,使用elasticsearch json对象的元素,合同桥分数进行计算

数据在这里:

{'took': 0, 'timed_out': False, '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0}, 'hits': {'total': 16, 'max_score': 1.0, 'hits': [{'_index': 'matchpoints', '_type': 'score', '_id': '6PKYGGgBjpp4O0gQgUu5', '_score': 1.0, '_source': {'board_number': '1', 'nsp': '4', 'ewp': '11', 'contract': '3NT', 'by': 'N', 'tricks': '11', 'nsscore': '460', 'ewscore ': '0'}}, {'_index': 'matchpoints', '_type': 'score', '_id': '7_KYGGgBjpp4O0gQgUu5', '_score': 1.0, '_source': {'board_number': '2', 'nsp': '3', 'ewp': '10', 'contract': '3C', 'by': 'E', 'tricks': '10', 'nsscore': '-130', 'ewscore ': '130'}}, {'_index': 'matchpoints', '_type': 'score', '_id': '6fKYGGgBjpp4O0gQgUu5', '_score': 1.0, …
Run Code Online (Sandbox Code Playgroud)

python elasticsearch

7
推荐指数
1
解决办法
195
查看次数

如何使用 Sequel 从数据库中选择一个字段

我在 PostgreSQL 中使用 Sinatra 和 Sequel。

身份验证后,我想通过打印他们的姓名来欢迎用户,但我不能只从数据库中获取用户名的值,它以散列形式出现。

查询是:

current_user = DB[:users].select(:username).where('password = ?', password).first
Run Code Online (Sandbox Code Playgroud)

得到的数据是:

Welcome, {:username=>"Rich"}
Run Code Online (Sandbox Code Playgroud)

这看起来很奇怪,我更喜欢读“欢迎,丰富”。

我在这里做错了什么?我在最后尝试了没有“first”的相同查询,但这也不起作用。

ruby postgresql sinatra sequel

5
推荐指数
1
解决办法
3568
查看次数

使用 Python、flask 和 SQLAlchemy 如何在 HTML 页面上打印数据库查询的结果?

我有一个非常简单的查询(刚开始使用 SQLAlchemy),我知道它正在工作,因为它在终端中打印,但不在 HTML 页面上打印,这就是问题所在。

如下:

from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import *
from models import db, Candidate, User, Template
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

some_engine = create_engine('databse_url')
Session = sessionmaker(bind=some_engine)
session = Session()

@application.route("/", methods=['GET', 'POST'])
def index():
    res = session.query(Template).all()
    for temp in res:
            print temp.spark_id
    return render_template('index.html')
Run Code Online (Sandbox Code Playgroud)

在终端中,打印了 2 个“spark_id”,但在 HTML 页面上我什么也没得到。

在 index.html 页面中,我有:

% if res %}
    {% for temp in res %}

        <p>{{ temp.spark_id }}</p>
        <p>{{ temp.created_at }}</p>

    {% endfor %} …
Run Code Online (Sandbox Code Playgroud)

python sqlalchemy flask flask-sqlalchemy

3
推荐指数
1
解决办法
2599
查看次数

如何使用续集 ORM 和 postgresl 对 sum 和 count 进行分组?

这对我来说太难了。是给杰瑞米的!

我有两个表(虽然我也可以设想需要加入第三个表),我想在同一个表中对一个字段求​​和并计算行数,同时与另一个表连接并以 json 格式返回结果。

首先需要求和的数据类型字段是numeric(10,2),插入的数据为params['amount'].to_f.

这些表是具有项目名称和公司 ID 的费用_项目以及具有公司 ID、项目和金额(仅提及关键列)的费用_项目 - “公司 ID”列已消除歧义。

所以,下面的代码:

expense_items = DB[:expense_projects].left_join(:expense_items, :expense_project_id => :project_id).where(:project_company_id => company_id).to_a.to_json
Run Code Online (Sandbox Code Playgroud)

工作正常,但当我添加

expense_total = expense_items.sum(:amount).to_f.to_json
Run Code Online (Sandbox Code Playgroud)

我收到一条错误消息,上面写着

TypeError - no implicit conversion of Symbol into Integer:
Run Code Online (Sandbox Code Playgroud)

所以,第一个问题是为什么以及如何解决这个问题?

然后我想加入两个表并从左侧(第一个表)中获取所有项目名称,并在第二个表中求和数量和计数项目。我试过了

DB[:expense_projects].left_join(:expense_items, :expense_items_company_id => expense_projects_company_id).count(:item).sum(:amount).to_json
Run Code Online (Sandbox Code Playgroud)

以及它的变体,所有这些都失败了。

我想要一个获取所有项目名称的结果(即使没有费用条目并返回如下内容:

project  item_count item_amount
pr 1      7           34.87
pr 2      0           0
Run Code Online (Sandbox Code Playgroud)

等等。如何通过一个查询以 json 格式返回结果来实现这一点?

非常感谢,伙计们。

ruby postgresql sequel

2
推荐指数
1
解决办法
625
查看次数

如何在弹性beanstalk上更新python Flask应用程序?

这是我在AWS上的第一个python-Flask应用程序.它引起了头痛.

我遵循的程序是:

mkdir myapp && cd myapp
virtualenv venv
source venv/bin/activate
pip install Flask SQLAlchemy twilio psycopg2 
pip freeze > requirements.txt
mkdir .ebextensions
cd .ebxtensions
nano application.config #content of this file below
packages:
  yum:
    postgresql93-devel: []

option_settings:
  - option_name: MANDRILL_APIKEY
    value: my_value
  - option_name: MANDRILL_USERNAME
    value: my_email_address
cd ..
deactivate
eb init
eb create
Run Code Online (Sandbox Code Playgroud)

经过一系列问题,包括选项设置和psycopg2,以上工作.

现在问题是当我在本地计算机上更改应用程序时如何更新.我试过如下:

git init
eb init
git add .
git commit -m "my first update"
git aws.push
Run Code Online (Sandbox Code Playgroud)

这不起作用,并返回错误消息,说这"git aws.push"不是一个合法的命令(或类似的东西).我也试过了"eb push".

这里有2个问题:

  1. 为什么上面的程序与git失败? …

python git amazon-web-services flask-sqlalchemy amazon-elastic-beanstalk

2
推荐指数
1
解决办法
671
查看次数

使用Python连接到AWS Elasticsearch实例

我有一个托管在AWS上的Elasticsearch实例.我可以通过我的终端与Curl连接.我现在正在尝试使用python elasticsearch包装器.我有:

from elasticsearch import Elasticsearch

client = Elasticsearch(host='https://ec2-xx-xx-xxx-xxx.us-west-2.compute.amazonaws.com', port=9200)
Run Code Online (Sandbox Code Playgroud)

并且查询是:

data = client.search(index="mynewindex", body={"query": {"match": {"email": "gmail"}}})
    for hit in data:
        print(hit.email)
    print data
Run Code Online (Sandbox Code Playgroud)

来自heroku的完整回溯是:

2016-07-22T14:06:06.031347+00:00 heroku[router]: at=info method=GET path="/" host=elastictest.herokuapp.com request_id=9a96d447-fe02-4670-bafe-efba842927f3 fwd="88.106.66.168" dyno=web.1 connect=1ms service=393ms status=500 bytes=456
2016-07-22T14:09:18.035805+00:00 heroku[slug-compiler]: Slug compilation started
2016-07-22T14:09:18.035810+00:00 heroku[slug-compiler]: Slug compilation finished
2016-07-22T14:09:18.147278+00:00 heroku[web.1]: Restarting
2016-07-22T14:09:18.147920+00:00 heroku[web.1]: State changed from up to starting
2016-07-22T14:09:20.838784+00:00 heroku[web.1]: Starting process with command `gunicorn application:application --log-file=-`
2016-07-22T14:09:20.834521+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2016-07-22T14:09:17.850918+00:00 heroku[api]: Deploy b7187d3 …
Run Code Online (Sandbox Code Playgroud)

python heroku amazon-ec2 amazon-web-services elasticsearch

2
推荐指数
3
解决办法
6788
查看次数

使用 Python 和 elasticsearch,如何遍历返回的 JSON 对象?

我的代码如下:

import json
from elasticsearch import Elasticsearch

es = Elasticsearch()

resp = es.search(index="mynewcontacts", body={"query": {"match_all": {}}})
    response = json.dumps(resp)
    data = json.loads(response)
    #print data["hits"]["hits"][0]["_source"]["email"]
    for row in data:
    print row["hits"]["hits"][0]["_source"]["email"]
    return "OK"
Run Code Online (Sandbox Code Playgroud)

产生这个截断的(为方便起见)JSON:

{"timed_out": false, "took": 1, "_shards": {"successful": 5, "total": 5, "failed": 0}, "hits": {"max_score": 1.0, "total": 7, "hits": [{"_index": "mynewcontacts", "_type": "contact", "_score": 1.0, 
"_source": {"email": "sharon.zhuo@xxxxx.com.cn", "position": "Sr.Researcher", "last": "Zhuo", "first": "Sharon", "company": "Tabridge Executive Search"}, "_id": "AVYmLMlKJVSAh7zyC0xf"},
{"_index": "mynewcontacts", "_type": "contact", "_score": 1.0, "_source": {"email": "andrew.springthorpe@xxxxx.gr.jp", …
Run Code Online (Sandbox Code Playgroud)

python json elasticsearch

2
推荐指数
1
解决办法
4582
查看次数