- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试设置一个非常简单的应用程序。我想将此应用程序创建为全栈应用程序,作为 future 项目的培训。所以我用 python 编写了一个后端,它通过 API (Flask/Connexion) 提供来自数据库 (SQLLite) 的数据。该 API 通过 Swagger 进行记录。数据库应该有一个表,其中每行有 2 个值:1. 姓名2.图像我很快就遇到了一个问题:我实际上不知道如何在 API 中处理图像。因此,我使用占位符创建了备份。到目前为止,图像只是另一个大部分为空的字符串。一切正常。但现在我希望能够通过 API 获取图像并将它们保存在数据库中。我完全不知道该怎么做。希望你们中的一位可以帮助我。
这是迄今为止我的代码:
SqlliteHandler.py
import sqlite3
conn = sqlite3.connect('sprint_name.db')
c = conn.cursor()
def connect_db():
global conn
global c
conn = sqlite3.connect('sprint_name.db')
c = conn.cursor()
c.execute("CREATE TABLE if not exists sprint_names ( name text, image text)")
def make_db_call(execute_statement, fetch_smth=""):
global c
connect_db()
print(execute_statement)
c.execute(execute_statement)
response = ""
if fetch_smth is "one":
response = transform_tuple_to_dict(c.fetchone())
if fetch_smth is "all":
response_as_tuples = c.fetchall()
response = []
for sug in response_as_tuples:
response.append(transform_tuple_to_dict(sug))
conn.commit()
conn.close()
return response
def transform_tuple_to_dict(my_tuple):
return {"name": my_tuple[0], "image": my_tuple[1]}
def add_name(suggestion):
name = suggestion.get("name")
image = "" if suggestion.get("image") is None else suggestion.get("image")
execute_statement = "SELECT * FROM sprint_names WHERE name='" + name + "'"
print(execute_statement)
alreadyexists = False if make_db_call(execute_statement, "one") is None else True
print(alreadyexists)
if not alreadyexists:
execute_statement = "INSERT INTO sprint_names VALUES ('" + name + "', '" + image + "')"
make_db_call(execute_statement)
def delete_name(suggestion_name):
execute_statement = "DELETE FROM sprint_names WHERE name='" + suggestion_name + "'"
print(execute_statement)
make_db_call(execute_statement)
def delete_all():
make_db_call("DELETE FROM sprint_names")
def get_all_names():
return make_db_call("SELECT * FROM sprint_names", "all")
def get_name(suggestion_name):
print(suggestion_name)
execute_statement = "SELECT * FROM sprint_names WHERE name='" + suggestion_name + "'"
print(execute_statement)
return make_db_call(execute_statement, "one")
def update_image(suggestion_name, suggestion):
new_name = suggestion.get("name" )
new_image = "" if suggestion.get("image") is None else suggestion.get("image")
execute_statement = "UPDATE sprint_names SET name='" + new_name + "', image='" + new_image + "' WHERE name='"\
+ suggestion_name + "'"
make_db_call(execute_statement)
RunBackEnd.py
from flask import render_template
import connexion
# Create the application instance
app = connexion.App(__name__, specification_dir='./')
# Read the swagger.yml file to configure the endpoints
app.add_api('swagger.yml')
# Create a URL route in our application for "/"
@app.route('/')
def home():
"""
This function just responds to the browser ULR
localhost:5000/
:return: the rendered template 'home.html'
"""
return render_template('home.html')
# If we're running in stand alone mode, run the application
if __name__ == '__main__':
app.run(port=5000)
Swagger.yml
swagger: "2.0"
info:
description: This is the swagger file that goes with our server code
version: "1.0.0"
title: Swagger REST Article
consumes:
- "application/json"
produces:
- "application/json"
basePath: "/api"
# Paths supported by the server application
paths:
/suggestions:
get:
operationId: SqlliteHandler.get_all_names
tags:
- suggestions
summary: The names data structure supported by the server application
description: Read the list of names
responses:
200:
description: Successful read names list operation
schema:
type: array
items:
properties:
name:
type: string
image:
type: string
post:
operationId: SqlliteHandler.add_name
tags:
- suggestions
summary: Create a name and add it to the names list
description: Create a new name in the names list
parameters:
- name: suggestion
in: body
description: Suggestion you want to add to the sprint
required: True
schema:
type: object
properties:
name:
type: string
description: Name you want to submit
image:
type: string
description: path to the picture of that name
responses:
201:
description: Successfully created name in list
/suggestions/{suggestion_name}:
get:
operationId: SqlliteHandler.get_name
tags:
- suggestions
summary: Read one name from the names list
description: Read one name from the names list
parameters:
- name: suggestion_name
in: path
description: name of the sprint name to get from the list
type: string
required: True
responses:
200:
description: Successfully read name from names list operation
schema:
type: object
properties:
name:
type: string
image:
type: string
put:
operationId: SqlliteHandler.update_image
tags:
- suggestions
summary: Update an image in the suggestion list via the name of the suggestions
description: Update an image in the suggestion list
parameters:
- name: suggestion_name
in: path
description: Suggestion you want to edit
type: string
required: True
- name: suggestion
in: body
schema:
type: object
properties:
name:
type: string
image:
type: string
responses:
200:
description: Successfully updated suggestion in suggestion list
delete:
operationId: SqlliteHandler.delete_name
tags:
- suggestions
summary: Delete a suggestion via its name from the suggestion list
description: Delete a suggestion
parameters:
- name: suggestion_name
in: path
type: string
required: True
responses:
200:
description: Successfully deleted a suggestion from the list
最佳答案
要在 SQLITE 中保存图像(不建议,最好将图像另存为文件并将路径保存在数据库中),请将其另存为字节数组(BLOB 存储类型,并不是列必须定义为 BLOB)。
在 SQL 中,您将字节数组指定为十六进制字符串。所以你读取图像并构建一个十六进制字符串
注意
Maximum length of a string or BLOB
The maximum number of bytes in a string or BLOB in SQLite is defined by the preprocessor macro SQLITE_MAX_LENGTH. The default value of this macro is 1 billion (1 thousand million or 1,000,000,000). You can raise or lower this value at compile-time using a command-line option like this:
-DSQLITE_MAX_LENGTH=123456789 The current implementation will only support a string or BLOB length up to 231-1 or 2147483647. And some built-in functions such as hex() might fail well before that point. In security-sensitive applications it is best not to try to increase the maximum string and blob length. In fact, you might do well to lower the maximum string and blob length to something more in the range of a few million if that is possible.
During part of SQLite's INSERT and SELECT processing, the complete content of each row in the database is encoded as a single BLOB. So the SQLITE_MAX_LENGTH parameter also determines the maximum number of bytes in a row.
The maximum string or BLOB length can be lowered at run-time using the sqlite3_limit(db,SQLITE_LIMIT_LENGTH,size) interface.
还有
Maximum Length Of An SQL Statement
The maximum number of bytes in the text of an SQL statement is limited to SQLITE_MAX_SQL_LENGTH which defaults to 1000000. You can redefine this limit to be as large as the smaller of SQLITE_MAX_LENGTH and 1073741824.
If an SQL statement is limited to be a million bytes in length, then obviously you will not be able to insert multi-million byte strings by embedding them as literals inside of INSERT statements. But you should not do that anyway. Use host parameters for your data. Prepare short SQL statements like this:
INSERT INTO tab1 VALUES(?,?,?); Then use the sqlite3_bind_XXXX() functions to bind your large string values to the SQL statement. The use of binding obviates the need to escape quote characters in the string, reducing the risk of SQL injection attacks. It is also runs faster since the large string does not need to be parsed or copied as much.
The maximum length of an SQL statement can be lowered at run-time using the sqlite3_limit(db,SQLITE_LIMIT_SQL_LENGTH,size) interface.
生成的 SQL 将类似于:-
INSERT INTO mytable (myimage) VALUES (x'fffe004577aabbcc33f1f8');
作为使用表的演示(稍微修改以包含“正确”列类型 BLOB,这几乎没有什么区别):-
DROP TABLE If EXISTS sprint_names;
CREATE TABLE if not exists sprint_names ( name text, image text, altimage BLOB);
INSERT INTO sprint_names VALUES
('SPRINT001',x'fffe004577aabbcc33f1f8',x'fffe004577aabbcc33f1f8'), -- obviously image would be larger
('SPRINT002',x'99008877665544332211f4d6e9c2aaa8b7b4',x'99008877665544332211f4d6e9c2aaa8b7b4')
;
SELECT * FROM sprint_names;
结果将是:-
如前所述,仅存储图像文件的路径要简单得多,当它归结为它时,可能很少需要图像作为数据。您不太可能查询图像组成的数据,而使用命名标准可以允许对存储的名称/路径进行有用的搜索/查询。
然而,与上述相反,在某些情况下(平均大小约为 100k 或更小(可能更多)的图像),SQLite 可以允许比文件系统 35% Faster Than The Filesystem 更快的访问速度。
关于python - 使用 Python Flask/Connexion 和 Swagger 处理 API 中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53190699/
我正在遵循Flask-potion教程并尝试保护我的api。我一直试图找出如何在User端点上设置权限,以使一个User无法查看另一个User的记录。这是我的代码: class UserResourc
项目设置 Python 3.5.3 flask 0.12.2 目录 . ├── Core │ ├── BackgroundProcessManager.py │ ├── FirebaseDat
我正在构建 flask 应用程序并决定这次尝试应用程序工厂方法,但是遇到了 flask 迁移的麻烦并且无法找出简单的解决方案。 请注意,我想将配置位置作为选项传递给脚本 管理.py: manager
我尝试通过以下示例代码来熟悉Flask-APScheduler插件:https://github.com/viniciuschiele/flask-apscheduler/blob/master/ex
我一周前刚刚了解了 Flask 和 JWT,所以我真的需要一些帮助。有人可以解释一下flask-jwt和flask-jwt-extended之间的区别吗? 最佳答案 Flask-JWT 没有那么多功能
我是 Flask 的新手,我只是想用它创建一个简单的市场。我的网站上有三种类型的用户 [卖家、买家、管理员]。我认为每种类型的用户都应该有自己的注册和登录,因为他们的角色应该提供不同类型的信息。另一方
基本上,我想做一些非常简单的事情:我想创建一个用于删除数据库中条目的表单。 模板正在创建一个包含所有条目的html表,没有任何麻烦。我现在的问题是:如何将其转换为每行都有链接的表单。 当然,我可以通过
我对Flask来说非常陌生,其中一个基本要求是我需要SEO友好的URL。 我说一条路线 @app.route('/sales/') @app.route(/sales/) def get_sales(
一直在为用户管理系统开发Flask-user,但是我看不到自定义登录页面和注册页面的方法。我使用pip安装了flask-user pip install flask-user 任何帮助,将不胜感激 最
我有一个奇怪的情况,不知道如何找到问题。 我已经创建了一个这样的蓝图 reportjobsmod = Blueprint('jobreports', __name__, url_prefix='/jo
我认为在 Flask 中拥有实例变量的正确方法是添加用户和 session ,但我正在尝试测试一个概念,我还不想经历所有这些。我试图让一个网络应用程序将图像加载到一个变量中,然后可以对其执行不同的图像
select = SelectField("City") form.select.choices = [(places['name'], places['name']) for places in p
这个问题在这里已经有了答案: Provide extra information to Flask's app.logger (2 个回答) 3年前关闭。 我正在运行一个 flask 应用程序。我想写
我当时正在编程一个非常不错的api,使用json从游戏服务器到我的网站空间获取一些json数据, 但是每次我使用angular发送请求时,我都会得到以下信息:127.0.0.1--[20 / Mar
我已经开发了一个上传表单,以将特定的.xlsx文件作为上传。要求是要处理非xlsx上载的任何异常(例如zip,exe文件)。我正在使用pyexcel库读取上传内容。我尝试创建以下代码来处理此异常: e
我使用此功能在网站上捕获404错误: @app.errorhandler(404) def page_not_found(e): logger.warning('User raised an
我正在尝试同时使用 Flask Restful 和 Flask SocketIO。我已经制作了一个 Flask Restful 应用程序,但现在我想使用 Flask SocketIO 在客户端和我的服
我有一些 Flask 应用程序,我通过设置 FLASK_APP 来运行它们。环境变量和调用 flask run .自 FLASK_DEBUG也设置了,每当我更改一些代码时,应用程序都可以方便地重新加载
我目前正在使用 Flask 构建一个应用程序。我正在努力访问 Flask 实例“app”以及 Flask-mail 实例“mail”。 下面是我的项目的样子: └── my-project ├
Remember-me是 parameter flask_login.login_user(user, remember=False, duration=None, force=False, fres
我是一名优秀的程序员,十分优秀!