flask管理数据库连接:内存: [英] flask manage db connection :memory:

查看:63
本文介绍了flask管理数据库连接:内存:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个flask应用程序,该应用程序需要存储来自请求的一些信息.该信息的寿命很短,如果服务器重新启动,我将不再需要它,因此我真的不需要持久性.

I have a flask application that needs to store some information from requests. The information is quite short-lived and if the server is restarted I do not need it any more - so I do not really need persistence.

我已在此处阅读了保存在其中的Sqlite数据库内存可以用于此目的.管理数据库连接的最佳方法是什么?在flask文档中,可以根据需要创建与数据库的连接,但是如果我关闭连接,则会删除我的数据库.

I have read here that an Sqlite database, which is held in memory can be used for that. What is the best way to manage the database connection? In the flask documentation connections to the database are created on demand, but my database will be deleted if I close the connection.

推荐答案

使用内存sqlite db的问题是无法从多个线程访问Sqlite内存数据库.

The problem with using an in memory sqlite db is that your Sqlite in-memory databases cannot be accessed from multiple threads.

http://www.sqlite.org/inmemorydb.html

为进一步解决该问题,您可能将有多个进程运行您的应用程序,这也使问题之外也可以使用内存中的全局变量.

To further the problem, you are likely going to have more than one process running your app, which makes using an in-memory global variable out of the question as well.

因此,除非可以确定您的应用仅需要一个线程或一个进程(这不太可能),否则您将需要:

So unless you can be certain that your app will only ever require a single thread or a single process (which is unlikely) You're going to need to either:

  1. 使用磁盘存储状态,例如磁盘上的sqlite db,甚至只是您解析的某些文件.
  2. 使用与应用程序分开运行的守护进程来管理状态.

我个人会选择选项2.

您可以使用memcached来运行,它可以在中央服务器上运行,甚至在只有一个服务器的情况下也可以在应用服务器上运行.这样一来,您就可以在内存中临时存储状态(包括python对象!),甚至可以设置数据过期时间的超时值,从事态上看,这可能对您的应用有用.

You can use memcached for this, running on a central server or even on your app server if you've only got one. This will allow you to store state (including python objects!) temporarily, in memory and you can even set timeout values for when the data should expire, which from the sound of things might be useful for your app.

由于您使用的是Flask,因此对于使用内存缓存提供了一些非常好的内置支持,请在此处查看:

Since you're using Flask, you've got some really good built-in support for using a memcached cache, check it out here: http://flask.pocoo.org/docs/patterns/caching/

关于使memcached在服务器上运行,实际上只是一个 apt-get yum install .让我知道您是否有疑问或挑战,我们将很乐意更新.

As for getting memcached running on your server, it's really just an apt-get or yum install away. Let me know if you have questions or challenges and I'll be happy to update.

这篇关于flask管理数据库连接:内存:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆