Home Php C# Sql C C++ Javascript Python Java Go Android Git Linux Asp.net Django .net Node.js Ios Xcode Cocoa Iphone Mysql Tomcat Mongodb Bash Objective-c Scala Visual-studio Apache Elasticsearch Jar Eclipse Jquery Ruby-on-rails Ruby Rubygems Android-studio Spring Lua Sqlite Emacs Ubuntu Perl Docker Swift Amazon-web-services Svn Html Ajax Xml Java-ee Maven Intellij-idea Rvm Macos Unix Css Ipad Postgresql Css3 Json Windows-server Vue.js Typescript Oracle Hibernate Internet-explorer Github Tensorflow Laravel Symfony Redis Html5 Google-app-engine Nginx Firefox Sqlalchemy Lucene Erlang Flask Vim Solr Webview Facebook Zend-framework Virtualenv Nosql Ide Twitter Safari Flutter Bundle Phonegap Centos Sphinx Actionscript Tornado Register | Login | Edit Tags | New Questions | 繁体 | 简体


10 questions online user: 23

15
votes
answers
41 views
+10

How to store Tornado logs to a file?

I've been facing issues where my server is throwing a 500 if the API isn't accessed for 30 mins at a stretch. To check the problem, I need to keep track of every single API request made. I'm using Tornado in front of Flask. This is my code so far:

import tornado.httpserver
import tornado.ioloop
import tornado.web
from flasky import app
from tornado.wsgi import WSGIContainer
from tornado.ioloop import IOLoop
from tornado.web import FallbackHandler

from tornado.log import enable_pretty_logging
enable_pretty_logging()


tr = WSGIContainer(app)

application = tornado.web.Application([
    (r".*", FallbackHandler, dict(fallback=tr)),
])

if __name__ == '__main__':
    application.listen(5000)
    IOLoop.instance().start()

Whats the most efficient way to store the logs to some file?

I tried doing this but it only works when the process exits with 0:

import sys
import time
timestr = time.strftime("%Y%m%d-%H%M%S")
filename = "C:/Source/logs/" + timestr + ".log"

class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open(filename, "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

    def flush(self):
        pass

sys.stdout = Logger()
up vote 15 down vote accepted favorite
沙发
+150
+50

You have used enable_pretty_logging which is good, and if you might note the documentation says you can pass in a logger. So what is a logger? Turns out Python has very extensive support for logging actions through the builtin logging module (which is mentioned in the documentation too). Generally, you need to set up handlers that write to some specific file, which you can do by

handler = logging.FileHandler(log_file_filename)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.info('foo')

This will log all info level entries (or higher) into the file. These loggers can be gathered by the logging.getLogger function, and you can explicitly select these as per the tornado documentation by

access_log = logging.getLogger("tornado.access")
app_log = logging.getLogger("tornado.application")
gen_log = logging.getLogger("tornado.general")

Simply append your handler to the logger that is generating the messages you want to log to a file. If it's the tornado.application generating the messages you want to see

handler = logging.FileHandler(log_file_filename)
app_log = logging.getLogger("tornado.application")
enable_pretty_logging()
app_log.addHandler(handler)

Or you can also use the builtin tornado options that enable this

tornado.options.options['log_file_prefix'].set(log_file_prefix)
tornado.options.parse_command_line()

非常感謝!內置龍捲風選項完全奏效。 - - 2016年6月14日,20:27,90

0
votes
answers
58 views
+10

有沒有關於python-flask的request.remote_addr的缺陷?或者它是可靠的(沒有反向代理)

0

Gooday to All,我寫下了一個非常敏感的Web應用程序,其功能就像文件瀏覽器,而不是使用sftp/ftp或ssh。它純粹使用http/https。我使用request.remote_addr來確定客戶端的IP地址。如果IP不在列表中,則拒絕。有沒有關於python-flask的request.remote_addr的缺陷?或者它是可靠的(沒有反向代理)

good_ips = ['127.0.0.1','192.168.1.10','192.168.1.1'] 
if request.remote_addr in good_ips: 
    pass 
else: 
    sys.exit() 

它工作正常,但我只想問,這是多麼可靠和安全:)。

如果ip不在列表中,這將是結果。其他明智的網站將運行良好:D。

謝謝你,美好的一天! Result if ip is not in the list

沙发
0
0

不,這不足以在您使用它時構建「敏感」服務。

查看https://en.wikipedia.org/wiki/IP_address_spoofing只是一個可能出錯的開始。

您應該使用身份驗證,例如使用公鑰(SSH支持)或密碼。 Kerberos也是一種可能性。

+0

哦。好的,謝謝你,先生。它不是主要的過濾器。只是一個避開陌生人的層;)但事情是,它不在私人IP上。我計劃做的是把我的公共ip放在那裏。作爲另一層。 (在這些主題上發現了一些問題 https://security.stackexchange.com/questions/105675/ip-spoofing-how-secure-is-to-control-access-by-user-s-public-ip-address) 所以,簡而言之,我不能依靠通過公共ip進行控制訪問。但不管怎麼說,只是爲了另一層保護而添加它;) – screaminghard

板凳
0
0

源IP過濾是否適合您的措施取決於您的確切場景和威脅模型。 @JohnZwinck是正確的,因爲它本身通常是不夠的,但對於某些應用程序來說,它可以。

雖然在單獨的IP數據包中僞造源IP很容易,但是http通過tcp,並且現代實現的tcp受到地址欺騙保護。儘管如此,較舊的TCP實現(在較早的操作系統中)仍然很脆弱。所以如果你的服務器有一個最新的操作系統,那麼欺騙一個源IP並不是一件簡單的事情。使用允許列表中的地址危害客戶端可能更容易。

可能出錯的另一件事與網絡地址轉換(NAT)有關。假設您將應用程序中的訪問限制爲內部IP地址(192.168.0.0/24)。一切正常,但是您的安全部門決定需要爲所有Web應用程序設置反向代理。代理已部署,並且所有工作都正常。然而,現在你的應用程序接收到來自代理服務器的所有請求wuth一個內部地址,所以應用程序中的限制沒有多大意義。客戶端也可能發生類似事件,在某些情況下,客戶端可能會在NAT後面,這意味着它們將具有相同的明顯的客戶端IP地址 - 這可能是好的或壞的。

最好的做法當然是要有正確的驗證(通過密碼,客戶證書,還是多因素等等,但是你固定希望它是),與IP限制是額外的層提供更多安全。

+0

感謝您的信息和見解先生:)是的。我決定在運行時實施登錄系統。 :)我也發現了一些關於代理的答案和解決方案(關於如何使用代理獲得客戶端的IP):)謝謝先生 – screaminghard

0
votes
answers
68 views
+10

flask - sqlalchemy - 自引用查詢

0

我嘗試在sqlalchemy中進行查詢以獲取在父級和子級上過濾的自引用關係。flask - sqlalchemy - 自引用查詢

category_country = Table('category_country', Base.metadata, 
    Column('category_id', Integer, ForeignKey('category.id'), primary_key=True), 
    Column('country_id', Integer, ForeignKey('country.id'), primary_key=True) 
) 

class Category(Base): 
    __tablename__ = "category" 
    id = Column(Integer, primary_key=True, autoincrement=True) 
    parent_id = Column(Integer, ForeignKey('category.id')) 
    subcategories = relationship("Category", backref=backref('parent', remote_side=id)) 
    countries = relationship(Country, secondary = category_country, backref='categories') 

class Country(Base): 
    __tablename__ = "country" 
    id = Column(Integer, primary_key=True) 

查詢

category = s.query(Category).join(Category.countries).options(contains_eager(Category.countries)).filter(Country.id == 1).filter(Category.id == category_id).join(Category.countries, aliased=True).join(Category.subcategories, aliased=True).options(contains_eager(Category.countries)).filter(Country.id == 1).first() 

,但它不工作。我需要找到孩子這是從國家1和其父是CATEGORY_ID和國家也是1

沙发
0
0

我沒有完全得到我的第一次讀你的模型/代碼,但我會解決這個的辦法是通過拆分自我指涉加入到子查詢()語句這樣的:

filter_by_country = (db.session.query(...) 
        .filter(...) 
        .subquery()) 

final_results = (db.session.query(...) 
       .join(filter_by_country, 
         db.and_(Category.id == filter_by_country.c.id, ..., ...)) 
       .options(...) 
       .filter(...) 
       .etc(...).first()) 

我發現這種模式可以幫助簡化這些類型的查詢。希望這可以幫助。

76
votes
answers
29 views
+10

Flask user authentication

I have an application that will use flask and mongodb; I will probably host it on rackspace.

I need to understand how flask authenticating works. I have not found much information on the subject. Is there a complete tutorial on how to roll your own solution? If not, I certainly would like to hear some thoughts on how you would approach it for a a flask app.

Big PS:

I just thought about it. I also need to open a real API. A part of that API will be used for AJAX on the front end. How do i secure that part of the app?

Can anyone explain API auth requests?

up vote 60 down vote accepted favorite
沙发
+600
+50

I would suggest using the flask-login extension, it makes session management really easy to add to your flask application, and provides a nice documentation which covers in details every aspect of the extension.

這是一個經證實的擴展嗎?你有沒有在生產中使用它?它有多安全? - pocorschi 2011年8月7日19:25

我只在一個應用程序中使用它,它看起來做得很好。但是,如果您真的擔心安全問題,那麼您可能想要自己查看其代碼(或者您使用的任何庫的代碼)。 - mdeous 2011年8月7日20:46

它相當安全,恕我直言。使用MD5,如果您擔心碰撞,可以將其更改為SHA2。 - Dhaivat Pandya 2011年8月10日9:31

雖然我沒有理由相信燒瓶登錄是不安全的,但我想在這裡提一下並提及炫耀這個或那個散列算法作為安全條是非常誤導的。安全!=算法和安全!=比特長! - Yaniv Aknin 12年12月24日中午12點

@DhaivatPandya flask-login根本不使用任何算法,因為由程序員來驗證 - 並存儲 - 憑證。 - dom013年9月2日10:59

+120

I don't think that flask has any authentication built-in, only support for tracking sessions.

Here are some snippets for basic HTTP authentication and authentication with some third-party providers. Otherwise you will need to roll your own or use a framework that has this baked in (like Django)

Here is a discussion thread on this topic with a useful link

謝謝rupello。這確實是我正在尋找的。如何滾動的一步一步。我自己的 。據我所知,燒瓶可以跟踪會話,所以我需要在某種檢查器中裝飾受限制的功能。但是ajax部分怎麼樣?還有..一篇論文將幫助我做出錯誤的選擇 - pocorschi 2011年8月7日13:57

+40

Flask-Login doesn't, technically, do authentication - it does session management, leaving the (tricky to securely implement) authentication details to you. Something like Flask-Security actually implements both session management and authentication (also nice-to-haves like password recovery/reset and the like), at the cost of having to have explicit support for your database.

0
votes
answers
83 views
+10

爲什麼SQLAlchemy關聯對象中的外鍵標記爲主鍵?

0

以下是sqlalchemy的文檔。爲什麼SQLAlchemy關聯對象中的外鍵標記爲主鍵?

注意如何在關聯類left_id和right_id,他們 第一標記爲ForeignKey的,然後primary_key =真

這是有道理的,我認爲他們應該是外鍵,因爲邏輯上它們是外鍵的其他兩張父母和孩子的桌子。

那麼,讓它們成爲主鍵的目的是什麼呢?

這是怎麼回事?請解釋。

class Association(Base): 
    __tablename__ = 'association' 
    left_id = Column(Integer, ForeignKey('left.id'), primary_key=True) 
    right_id = Column(Integer, ForeignKey('right.id'), primary_key=True) 
    extra_data = Column(String(50)) 
    child = relationship("Child", back_populates="parents") 
    parent = relationship("Parent", back_populates="children") 

class Parent(Base): 
    __tablename__ = 'left' 
    id = Column(Integer, primary_key=True) 
    children = relationship("Association", back_populates="parent") 

class Child(Base): 
    __tablename__ = 'right' 
    id = Column(Integer, primary_key=True) 
    parents = relationship("Association", back_populates="child") 
沙发
0
0

這不是SQLAlchemy特有的。這就是如何設計many-to-many relationships,這是基於關係數據庫設計的原則。

在多對多關係中,需要一個附加表,也稱爲關聯表,它將第一個表中的條目與第二個表中的對應條目進行映射。

當關聯表被定義時,我們需要一些主鍵來唯一標識關聯表中的記錄。使用主鍵可創建索引,從而加快聯合操作和搜索記錄。

那麼,爲什麼所有的外鍵都作爲關聯表的主鍵的一部分呢? 這是爲了確保沒有重複條目atable A和記錄bTable B。換句話說,要確保關係的唯一性,從而避免重複關係。

可以在不將外鍵聲明爲主鍵的情況下創建關聯表。但這是不建議。通過這樣做,除非明確創建索引,否則聯接操作變得緩慢。而且,有很好的機會可以重複記錄Table ATable B之間的關係

0
votes
answers
82 views
+10

如何設置SQLAlchemy中兩個表之間的關係?

0

我有兩個表:如何設置SQLAlchemy中兩個表之間的關係?

  1. 公告
  2. AnnouncementsSchedule

關係是關鍵one(Announcements)many(AnnouncementsSchedule)

Announcements.id = AnnouncementsSchedule.announcements_id 

我試圖描述SQLAlchemy的機型:

第一個表被描述爲模型:

class Announcements(db.Model): 
    __tablename__ = 'announcements' 
    id = db.Column(db.Integer, primary_key=True) 
    name = db.Column(db.String(150), nullable=False) 
    text = db.Column(db.Text(), nullable=False) 
    category = db.Column(db.Integer(), nullable=False) 
    subcategory = db.Column(db.Integer(), nullable=False) 
    offer_type = db.Column(db.Integer(), nullable=False) 
    url = db.Column(db.String(150), nullable=True) 
    status = db.Column(db.Integer(), nullable=False) 
    #children = relationship("AnnouncementsSchedule", back_populates="announcements") 

二是:

class AnnouncementsSchedule(db.Model): 
    __tablename__ = 'announcements_schedule' 
    id = Column(Integer, primary_key=True) 
    week_day = db.Column(db.Integer(), nullable=True) 
    week_all = db.Column(db.Integer(), nullable=False) 
    time = db.Column(db.Time(), nullable=False) 
    announcement_id = Column(Integer, ForeignKey('announcements.announcements_id')) 

我做什麼了?

+0

你有沒有一個得到錯誤?你有什麼問題? –

沙发
0
0

你有列名錯誤(公告沒有announcement_id):

# announcement_id = Column(Integer, ForeignKey('announcements.announcements_id')) 
# change to -> 
announcement_id = Column(Integer, ForeignKey('announcements.id')) 
+0

謝謝,那麼如何從相關表中獲取數據? – Jessie

+0

announcement = relationship(「Announcements」,back_populates =「schedule」) - 在第一個模型上,put - > schedules = relationship(「AnnouncementsSchedule」,back_populates =「announcement」) –

0
votes
answers
30 views
+10

閃爍的500內部服務器錯誤屏幕燒瓶與Python

0

簡單的問題,我希望... 我在開發時收到500內部錯誤,並希望將它們閃爍到瀏覽器屏幕,以便於更換時間。用Flask和Python做這個最簡單的方法是什麼? 謝謝。閃爍的500內部服務器錯誤屏幕燒瓶與Python

沙发
0
1

寫custome錯誤頁面,在燒瓶神社模板,顯示要閃爍屏幕上的方式

from flask import render_template 

@app.errorhandler(500) 
def page_not_found(e): 
    return render_template('500.html'), 404 

#An example template might be this for your 5000.html, you can write 
#your own through this code: 

{% extends "layout.html" %} 
{% block title %}Page Not Found{% endblock %} 
{% block body %} 
    <h1>Page Not Found</h1> 
    <p>What you were looking for is just not there. 
    <p><a href="{{ url_for('index') }}">go somewhere nice</a> 
{% endblock %} 
+0

真棒!不知道最簡單的方法是什麼,但這可能會奏效,謝謝! – douglasrcjames

板凳
0
-1

500,這意味着有你demo.may一些錯誤,以及把你的錯誤信息

0
votes
answers
39 views
+10

在同一個Apache服務器上運行mod_wsgi(Flask)應用程序和非mod_wsgi應用程序

2

我通過python CGI腳本(Apache2.4)繼承了在AWS EC2 Windows實例和WAMP服務器上運行的Web應用程序。我正在將Web應用程序轉換爲Flask,但無法在測試/推出我的Flask應用程序時取下現有的應用程序。在同一個Apache服務器上運行mod_wsgi(Flask)應用程序和非mod_wsgi應用程序

目前所有的腳本都位於WAMP WWW文件夾和互聯網的IP地址/「filename.extension」

上被訪問有沒有爲我Virtualhosts配置,讓我跑的方式在www文件夾中存在應用程序,並在同一臺Apache服務器上使用mod_WSGI託管我的Flask應用程序?

我最好只設置一個新的AWS實例來託管我的Flask應用程序,並且只是將所有內容都移走?

謝謝

+0

我會親自設置新的EC2實例和運行Linux的一番風味。一舉兩得! – BrettJ

沙发
0
0

您可以掛載WSGI應用程序在一個子網址,所以不會干擾。或者,使用AddHandler並指定WSGI腳本使用.wsgi擴展名,因此如果它們使用.py擴展名,則不會干擾現有的Python CGI腳本。

有關選項的詳細信息閱讀:

12
votes
answers
50 views
+10

Flask app hangs while processing the request

I have a simple flask app, single page, upload html and then do some processing on it on the POST; at POST request; i am using beautifulsoup, pandas and usually it takes 5-10 sec to complete the task.

at the end i export the resultant dataframe to excel with pandas(with the update of the previous stored excel if present). and on GET request i return the result of this dataframe.

Now issue is... app gives no response while those 5-10 sec.; even if i visit my app from another computer; it will show after the completion of those 5-10 sec. It means if any user of this app has uploaded his file; then rest others have to wait till his job completes.

i have even added the below mentioned code in my app; but no improvement.

from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop

if __name__ == '__main__':
    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(5657)
    IOLoop.instance().start()

also my system and python version is as below.. .

>>> sys.version
'2.7.5 |Anaconda 1.8.0 (32-bit)| (default, Jul  1 2013, 12:41:55) [MSC v.1500 32 bit (Intel)]'

Note: i want to move it to python3.3, and wanted to remain on my windows 7 machine!!

up vote 12 down vote accepted favorite
沙发
+120
+50

Tornado is, typically, a single-threaded web server. If you write code specially for Tornado's asynchronous style you can process multiple requests concurrently, but in your case you aren't doing that; you're just using Tornado to serve requests with Flask, one at a time.

Remove Tornado and try using Flask's multithreaded option:

app.run(threaded=True)

@Jesse:現在它正在運行..我也嘗試在windows上製作進程= 10; 它停在os.fork(); 好的,然後我必須將我的應用程序移動到更好的備用; 喜歡linux機器; 這樣我就要指定進程數了?那麼有什麼方法可以讓我的應用程序自動在每個新請求上添加新進程? - namit 2014年3月11日14:12

請參閱run_simple的文檔,這裡:werkzeug.pocoo.org/docs/serving/#werkzeug.serving.run_simple app.run的所有參數都傳遞給run_simple。在Windows上,使用多線程。在Linux上,使用多個線程和/或進程。 - A. Jesse Jiryu Davis 2014年3月11日16:18

0

If you're using WSGI's run_simple function just add the threaded=true param.

Example:

run_simple('0.0.0.0', 9370, application, use_reloader=True, use_debugger=True, threaded=True)
0
votes
answers
64 views
+10

獲取下一行peewee

0

我創建一個使用瓶和peewee獲取下一行peewee

這是樣本查詢來獲取當前後使用url

total_data = wired_model.EN.select().order_by(wired_model.EN.id.desc()) 
post = total_data.where(wired_model.EN.url == url).get() 

我使用total_data拿到最近的職位,現在我博客要顯示一個鏈接到下一篇文章和以前的帖子在目前的崗位,有一個簡單的方法來做到這在peewee像next_row()

沙发
0
1

使用「偏移」:

.limit(1).offset(1)