简体   繁体   English

用于 RethinkDB 匹配(正则表达式)查询的 Python unicode 转义

[英]Python unicode escape for RethinkDB match (regex) query

I am trying to perform a rethinkdb match query with an escaped unicode user provided search param:我正在尝试使用转义的 unicode 用户提供的搜索参数执行 rethinkdb 匹配查询:

import re
from rethinkdb import RethinkDB

r = RethinkDB()

search_value = u"\u05e5"  # provided by user via flask
search_value_escaped = re.escape(search_value)  # results in u'\\\u05e5' ->
    # when encoded with "utf-8" gives "\ץ" as expected.

conn = rethinkdb.connect(...)

results_cursor_a = r.db(...).table(...).order_by(index="id").filter(
    lambda doc: doc.coerce_to("string").match(search_value)
).run(conn)  # search_value works fine

results_cursor_b = r.db(...).table(...).order_by(index="id").filter(
    lambda doc: doc.coerce_to("string").match(search_value_escaped)
).run(conn)  # search_value_escaped spits an error

The error for search_value_escaped is the following: search_value_escaped 的错误如下:

ReqlQueryLogicError: Error in regexp `\ץ` (portion `\ץ`): invalid escape sequence: \ץ in:
r.db(...).table(...).order_by(index="id").filter(lambda var_1: var_1.coerce_to('string').match(u'\\\u05e5m'))
                                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^         

I tried encoding with "utf-8" before/after re.escape() but same results with different errors.我尝试在 re.escape() 之前/之后使用“utf-8”进行编码,但结果相同但错误不同。 What am I messing?我在胡闹什么? Is it something in my code or some kind of a bug?它是我的代码中的某些内容还是某种错误?

EDIT: .coerce_to('string') converts the document to "utf-8" encoded string.编辑: .coerce_to('string') 将文档转换为“utf-8”编码的字符串。 RethinkDB also converts the query to "utf-8" and then it matches them hence the first query works even though it looks like a unicde match inside a string. RethinkDB 还将查询转换为“utf-8”,然后匹配它们,因此第一个查询可以工作,即使它看起来像字符串中的 unide 匹配。

From what it looks like RethinkDB rejects escaped unicode characters so I wrote a simple workaround with a custom escape without implementing my own logic of replacing characters (in fear that I must miss one and create a security issue).从表面上看,RethinkDB 拒绝转义的 unicode 字符,所以我用自定义转义编写了一个简单的解决方法,而没有实现我自己的替换字符的逻辑(担心我必须错过一个并造成安全问题)。

import re

def no_unicode_escape(u):
    escaped_list = []

    for i in u:
        if ord(i) < 128:
            escaped_list.append(re.escape(i))
        else:
            escaped_list.append(i)

    rv = "".join(escaped_list)
    return rv

or a one-liner:或单线:

import re

def no_unicode_escape(u):
    return "".join(re.escape(i) if ord(i) < 128 else i for i in u)

Which yields the required result of escaping "dangerous" characters and works with RethinkDB as I wanted.这产生了转义“危险”字符所需的结果,并按照我的需要与 RethinkDB 一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM