Does Tornado support array cookie?
In PHP, we set array cookie by
setcookie('UserTable[Name]','Tinywan',time()+3600);
setcookie('UserTable[Age]','24',time()+3600);
setcookie('UserTable[Email]','7514#xxx.com',time()+3600);
But in tornado, it doesn't work!
self.set_cookie('UserTable[Name]', 'Tinywan', expires_days=30)
self.set_cookie('UserTable[Age]', '24', expires_days=30)
self.set_cookie('UserTable[Email]', '7514#xxx.com', expires_days=30)
It because of the Python Http cookie module raise the error when illegal charater present in the Key
from http import cookies
C = cookies.SimpleCookie()
C['UserTable[Name]'] = 'Tinywan'
Traceback
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/http/cookies.py", line 521, in __setitem__
self.__set(key, rval, cval)
File "/usr/local/lib/python3.6/http/cookies.py", line 511, in __set
M.set(key, real_value, coded_value)
File "/usr/local/lib/python3.6/http/cookies.py", line 380, in set
raise CookieError('Illegal key %r' % (key,))
http.cookies.CookieError: Illegal key 'UserTable[Name]'
>>> C['UserTableName'] = 'Tinywan'
You're using illegal characters for Cookie name, that is, [ and ] characters are illegal.
From MDN documentation:
A <cookie-name> can be any US-ASCII characters except control characters (CTLs), spaces, or tabs. It also must not contain a separator character like the following: ( ) < > # , ; : \ " / [ ] ? = { }.
You don't really need these characters. UserTableName should work fine.
Related
This works:
ss = 'insert into images (file_path) values(?);'
dddd = (('dd1',), ('dd2',))
conn.executemany(ss, dddd)
However this does not:
s = 'insert into images (file_path) values (:v)'
ddddd = ({':v': 'dd11'}, {':v': 'dd22'})
conn.executemany(s, ddddd)
Traceback (most recent call last):
File "/Users/Wes/.virtualenvs/ppyy/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 3035, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-31-a999de59f73b>", line 1, in <module>
conn.executemany(s, ddddd)
ProgrammingError: You did not supply a value for binding 1.
I am wondering if it is possible to use named parameters with executemany and, if so, how.
The documentation at section 11.13.3 talks generally about parameters but doesn't discuss the two styles of parameters that are described for other flavors of .executexxx().
I have checked out Python sqlite3 execute with both named and qmark parameters which does not pertain to executemany.
The source shows that execute() simply constructs a one-element list and calls executemany(), so the problem is not with executemany() itself; the same call fails with execute():
>>> conn.execute('SELECT :v', {':v': 42})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.ProgrammingError: You did not supply a value for binding 1.
As shown in the Python documentation, named parameters do not include the colon:
# And this is the named style:
cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})
So you have to use ddddd = ({'v': 'dd11'}, {'v': 'dd22'}).
The : isn't part of the parameter name.
>>> s = 'insert into images (file_path) values (:v)'
>>> ddddd = ({'v': 'dd11'}, {'v': 'dd22'})
>>> conn.executemany(s, ddddd)
<sqlite3.Cursor object at 0x0000000002C0E500>
>>> conn.execute('select * from images').fetchall()
[(u'dd11',), (u'dd22',)]
text="""[{"token":"03AJzQf7P5tfAY0T8yGDlF_aoPkLgz9-F7aiXzvViQqaaRmcJeFuIq96vmLoPXVK1GW-Fs8xp6OmJWvFvyNa3ayMpvaLkb6R sVkjjWBjqVIW4ziWeHk--Vrd8zVaA-Pt8VxMdoDBYxjRRrCNdeQN-Fk_-Wywb5XceJGdPJbMDZ-BoOB8l3Gq4bFwJTVu56zLT-4fbAsLWqRI7TjEswJ_y2-6NlEOyTTxFblzlZLYFh7urRx2Wra_gdP0-uUxoZydZBzbiPetcYmGo9b1B69-Pmb7akK7aqLUN03mvC3t1bn4u0ZvJGWjBmqhv81QoP3J1u-_Xh p34_dhspsjDpgfxYcHTI3e3yAir_QQ","timestamp":"2017-10-11T23:40:13.436Z"},{"token":"03AJzQf7Mmj_KZVl39Ob1_YnvsJuj4vFS o8ZWXNUJjSEjZqNyH8puB035sZYbQdPLVdOoX8ljyGeDYvxk6Kkf3Sc16EAS0bg0cXUAXzs6LAr3jDZmtW38TjWN5qbykIN_-s0-YpX6F0XJ4Hw3GDl vVkxmAk1btZewbeUp1nwMeM9BGJxkJZ5_2LRCGTERPGICKU4P897_FYcduADw5j1wEd9Yp7TdczRkgkY3qpsNcxlrF_rXv7DAvUxkg2_fussc3RkRgq ZueTMPkDN7B5BYiTBqVeXJ48Lvm6-1R86HgyrcDAPaZ1xMY0JxzMSvU26rChpomXFLERLfxijDNrixfGeh8hSCa0dX1HiLac8yOERKRcbBk1kXLOK8" ,"timestamp":"2017-10-11T23:40:29.916Z"}]"""
I would like to parse out this string, and put it into a list. I only want the token value to be store in the list.
My current code (not working):
token = re.search('(?<="token":").*?"', text)
print(token.group(0))
print(token.group(1))
the output:
03AJzQf7P5tfAY0T8yGDlF_aoPkLgz9-F7aiXzvViQqaaRmcJeFuIq96vmLoPXVK1GW-Fs8xp6OmJWvFvyNa3ayMpvaLkb6RsVkjjWBjqVIW4ziWeHk--Vrd8zVaA-Pt8VxMdoDBYxjRRrCNdeQN-Fk_-Wywb5XceJGdPJbMDZ-BoOB8l3Gq4bFwJTVu56zLT-4fbAsLWqRI7TjEswJ_y2-6NlEOyTTxFblzlZLYFh7urRx2Wra_gdP0-uUxoZydZBzbiPetcYmGo9b1B69-Pmb7akK7aqLUN03mvC3t1bn4u0ZvJGWjBmqhv81QoP3J1u-_Xhp34_dhspsjDpgfxYcHTI3e3yAir_QQ"
Error for token.group(1):
Traceback (most recent call last):
File "main.py", line 45, in <module>
print(token.group(1))
IndexError: no such groupuUxoZydZBzbiPetcYmGo9b1B69-Pmb7akK7aqLUN03mvC3t1bn4u0ZvJGWjBmqhv81QoP3J1u-_Xhp34_dhspsjDpgfxYcHTI3e3yAir_QQ"
Your text is a json string. You can use json.loads to convert from json string to a list of dict.
import json
text="""[{"token":"03AJzQf7P5tfAY0T8yGDlF_aoPkLgz9-F7aiXzvViQqaaRmcJeFuIq96vmLoPXVK1GW-Fs8xp6OmJWvFvyNa3ayMpvaLkb6R sVkjjWBjqVIW4ziWeHk--Vrd8zVaA-Pt8VxMdoDBYxjRRrCNdeQN-Fk_-Wywb5XceJGdPJbMDZ-BoOB8l3Gq4bFwJTVu56zLT-4fbAsLWqRI7TjEswJ_y2-6NlEOyTTxFblzlZLYFh7urRx2Wra_gdP0-uUxoZydZBzbiPetcYmGo9b1B69-Pmb7akK7aqLUN03mvC3t1bn4u0ZvJGWjBmqhv81QoP3J1u-_Xh p34_dhspsjDpgfxYcHTI3e3yAir_QQ","timestamp":"2017-10-11T23:40:13.436Z"},{"token":"03AJzQf7Mmj_KZVl39Ob1_YnvsJuj4vFS o8ZWXNUJjSEjZqNyH8puB035sZYbQdPLVdOoX8ljyGeDYvxk6Kkf3Sc16EAS0bg0cXUAXzs6LAr3jDZmtW38TjWN5qbykIN_-s0-YpX6F0XJ4Hw3GDl vVkxmAk1btZewbeUp1nwMeM9BGJxkJZ5_2LRCGTERPGICKU4P897_FYcduADw5j1wEd9Yp7TdczRkgkY3qpsNcxlrF_rXv7DAvUxkg2_fussc3RkRgq ZueTMPkDN7B5BYiTBqVeXJ48Lvm6-1R86HgyrcDAPaZ1xMY0JxzMSvU26rChpomXFLERLfxijDNrixfGeh8hSCa0dX1HiLac8yOERKRcbBk1kXLOK8" ,"timestamp":"2017-10-11T23:40:29.916Z"}]"""
mylist = json.loads(text)
token = ' '.join(mylist[0]['token'].split()).split()
I am using python 2.7.8 to write a small python code that reads a rule in a form A ==> B by using regex and return it in a form of 'A, B'.
This is my code:
import re
def fixp1(s):
pattern = re.compile("(?P<g1>([A-Z0-9a-z]|\?)*):(?P<g2>([A-Z0-9a-z]|\?)*)")
return eval(pattern.sub("('\g<g1>', '\g<g2>')", s))
x = "[ABCD:NP, [PQR:?TAG1]] ==> [XXX:?P]"
def readrule(r):
r.split("==>")
return [fixp1(r[0].strip()), fixp1(r[1].strip())]
When I test this code:
>>> readrule(x)
I got the following error message:
readrule(y)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../patterns.py", line 12, in readrule
return [fixp1(r[0].strip()), fixp1(r[1].strip())]
File ".../patterns.py", line 5, in fixp1
return eval(pattern.sub("('\g<g1>', '\g<g2>')", s))
File "<string>", line 1
[
^
SyntaxError: unexpected EOF while parsing
>>>
I think this problem happened because I couldn't add '[' and ']' in here
([A-Z0-9a-z]|\?)
If that's right, how to do it? if not; where is my mistake?
Remove the eval command, the RegEx.sub returns a string which is your match with the replacements applied, you cannot evaluate the string. This yields the SyntaxError you are seeing.
If you want to include [] in your patterns, you need to escape them with \:
pattern = re.compile(r'[\[\]0-9]+')
would match strings like '[1234]'.
the error is this:
mini: mkrule www.google.com therule
Traceback (most recent call last):
File "C:/Users/t11/Dropbox/2.0/cmd2.0.py", line 88, in <module>
MiniDownloader().cmdloop()
File "C:\Python27\lib\cmd.py", line 142, in cmdloop
stop = self.onecmd(line)
File "C:\Python27\lib\cmd.py", line 221, in onecmd
return func(arg)
File "C:/Users/t11/Dropbox/2.0/cmd2.0.py", line 75, in do_mkrule
functions2.write(self.RulesDir+site, xpath)
File "C:\Users\t11\Dropbox\2.0\functions2.py", line 12, in write
with open(path_file, mod) as FileObject:
IOError: [Errno 22] invalid mode ('w') or filename: 'C:\\Users\\t11\\Dropbox\\2.0\\Rules\\https://www.google.com'
Process finished with exit code 1
i am using the cmd module
and this is the function:
def write(path_file, data, mod="w", writeover=False):
""" gets file path + name and contents
check if the name is taken and if not write it (return's True if successful and False if not) """
if os.path.exists(path_file) and writeover is not True:
return False
else:
with open(path_file, mod) as FileObject:
FileObject.write(data)
FileObject.flush()
return True
and i called the function here:
def do_mkrule(self, s):
s = s.split()
if len(s) != 2:
self.help_mkrule()
return
site = s[0]
xpath = s[1]
site = functions2.url_check(site)
if xpath == "del":
os.remove(self.RulesDir+site)
print "file "+site+" removed"
else:
if site != False:
functions2.write(self.RulesDir+site, xpath)
print "rule for "+site+" created"
The intent of the function is to get file path, name and contents, check if the name is taken and if not write it.
It should return True if successful and False if unsuccessful.
The error message says it:
IOError: [Errno 22] invalid mode ('w') or filename: 'C:\\Users\\t11\\Dropbox\\2.0\\Rules\\https://www.google.com'
The filename you passed to the function is invalid. There are many characters that Windows will not accept in filenames, including colons (:) and forward slashes (/).
You could get rid of them (a good contender is to replace invalid characters with underscores) or find another way of encoding the site's name in the filename, such as by having an index that lists the names (e.g. a file named "sites.json" with mappings from site to filename).
How to understand the Url patterns for eg. (?P<slug>[-\w]+)/$ in django url.py
This url: (?P<slug>[-\w]+)/$
Says that you are passing a variable to your view called slug could be any digits or letters and -
your view is like this:
def my_view(request, slug):
....
hope it helps...
First Mastering Regular Expressions, then 7.2.1 - Regular Expression Syntax
I think it is not a valid regex pattern.
"[-\w]+" will get "word and -", something like "a-b9-c-" or "---"
(?P...) is a "Named Group". If you don't give its name, python (mine is 2.7) will raise error.
>>> m = re.match("(?P<e>[-\w]+)/$", "a-b-c-/")
>>> m.group('e')
'a-b-c-'
>>> m = re.match("(?P[-\w]+)/$", "a-b-c-/")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/re.py", line 137, in match
return _compile(pattern, flags).match(string)
File "/usr/lib/python2.7/re.py", line 244, in _compile
raise error, v # invalid expression
sre_constants.error: unknown specifier: ?P[
Note that slug fields might also include digits (not just letters and the dash), so you want to alter it to say something like:
SLUG = '(?P<slug>[\w\d-]+)'
I hope this helpful to you...