How to understand the Url patterns in django url.py - django

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...

Related

How to solve AttributeError in python active_directory?

Running the below script works for 60% of the entries from the MasterGroupList however suddenly fails with the below error. although my questions seem to be poor ou guys have been able to help me before. Any idea how I can avoid getting this error? or what is trhoughing off the script? The masterGroupList looks like:
Groups Pulled from AD
SET00 POWERUSER
SET00 USERS
SEF00 CREATORS
SEF00 USERS
...another 300 entries...
Error:
Traceback (most recent call last):
File "C:\Users\ks185278\OneDrive - NCR Corporation\Active Directory Access Scr
ipt\test.py", line 44, in <module>
print group.member
File "C:\Python27\lib\site-packages\active_directory.py", line 805, in __getat
tr__
raise AttributeError
AttributeError
Code:
from active_directory import *
import os
file = open("C:\Users\NAME\Active Directory Access Script\MasterGroupList.txt", "r")
fileAsList = file.readlines()
indexOfTitle = fileAsList.index("Groups Pulled from AD\n")
i = indexOfTitle + 1
while i <= len(fileAsList):
fileLocation = 'C:\\AD Access\\%s\\%s.txt' % (fileAsList[i][:5], fileAsList[i][:fileAsList[i].find("\n")])
#Creates the dir if it does not exist already
if not os.path.isdir(os.path.dirname(fileLocation)):
os.makedirs(os.path.dirname(fileLocation))
fileGroup = open(fileLocation, "w+")
#writes group members to the open file
group = find_group(fileAsList[i][:fileAsList[i].find("\n")])
print group.member
for group_member in group.member: #this is line 44
fileGroup.write(group_member.cn + "\n")
fileGroup.close()
i+=1
Disclaimer: I don't know python, but I know Active Directory fairly well.
If it's failing on this:
for group_member in group.member:
It could possibly mean that the group has no members.
Depending on how phython handles this, it could also mean that the group has only one member and group.member is a plain string rather than an array.
What does print group.member show?
The source code of active_directory.py is here: https://github.com/tjguk/active_directory/blob/master/active_directory.py
These are the relevant lines:
if name not in self._delegate_map:
try:
attr = getattr(self.com_object, name)
except AttributeError:
try:
attr = self.com_object.Get(name)
except:
raise AttributeError
So it looks like it just can't find the attribute you're looking up, which in this case looks like the 'member' attribute.

praw.errors.Forbidden: HTTP error when using Reddit get_flair_list

I am trying to get the comments for each Reddit post.
This is the way I am using to get flair list:
import praw
import webbrowser
r = praw.Reddit('OAuth testing example by u/_Daimon_ ver 0.1 see '
'https://praw.readthedocs.org/en/latest/'
'pages/oauth.html for source')
r.set_oauth_app_info(client_id='[client id]',
client_secret='[client secret]',
redirect_uri='http://localhost/authorize_callback')
url = r.get_authorize_url('uniqueKey', 'modflair', True)
webbrowser.open(url)
Then I got the code from the returned url, and I put the code in the access information, like this:
access_information = r.get_access_information('[returned code]')
Then when I am trying to call get_fliar_list() just like PRAW tutorial, like this:
item = next(r.get_subreddit('travel').get_flair_list())
It gives me an error, showing:
Traceback (most recent call last):
File "", line 1, in
File "/Library/Python/2.7/site-packages/praw-3.4.0-py2.7.egg/praw/init.py", line 565, in get_content
page_data = self.request_json(url, params=params)
File "", line 2, in request_json
File "/Library/Python/2.7/site-packages/praw-3.4.0-py2.7.egg/praw/decorators.py", line 116, in raise_api_exceptions
return_value = function(*args, **kwargs)
File "/Library/Python/2.7/site-packages/praw-3.4.0-py2.7.egg/praw/init.py", line 620, in request_json
retry_on_error=retry_on_error)
File "/Library/Python/2.7/site-packages/praw-3.4.0-py2.7.egg/praw/init.py", line 452, in _request
_raise_response_exceptions(response)
File "/Library/Python/2.7/site-packages/praw-3.4.0-py2.7.egg/praw/internal.py", line 208, in _raise_response_exceptions
raise Forbidden(_raw=response)
praw.errors.Forbidden: HTTP error
Here's the link of that PRAW tutorial: PRAW tutorial
Do you know how to solve this problem? How can I call get_flair_list() to get all the comments of a Reddit post?
There are a few things potentially going on here.
The first issue (And the most likely) Is that you are logging in wrong.
r = praw.Reddit('OAuth testing example by u/_Daimon_ ver 0.1 see '
'https://praw.readthedocs.org/en/latest/'
'pages/oauth.html for source')
DONT DO THIS, EVER
Even if the syntax in this command was correct (you dont have the commas), this makes your code INCREDIBLY hard to read. The most readable way is to have r = praw.Reddit('OAuth-testing') (the OAuth-testing bit can be whatever you want, as long as it is the same as in your praw.ini file.), then setup your praw.ini file as such:
[DEFAULT]
# A boolean to indicate whether or not to check for package updates.
check_for_updates=True
# Object to kind mappings
comment_kind=t1
message_kind=t4
redditor_kind=t2
submission_kind=t3
subreddit_kind=t5
# The URL prefix for OAuth-related requests.
oauth_url=https://oauth.reddit.com
# The URL prefix for regular requests.
reddit_url=https://www.reddit.com
# The URL prefix for short URLs.
short_url=https://redd.it
[OAuth-testing]
user_agent=USER-AGENT-HERE
username=REDDIT-ACCOUNT-USERNAME
password=REDDIT-ACCOUNT-PASSWORD
client_id=REDDIT-APP-CLIENT-ID
client_secret=REDDIT-APP-CLIENT-SECRET
Just as an additional note, get_flair_list() also requires moderator access, as documented here
Also, you ask at the bottom:
How can I call get_flair_list() to get all the comments of a Reddit post?
This would not be how you get all the comments of a post, if that is what you want to do you can read this tutorial in the PRAW docs.
If you have any further questions don't hesitate to comment on this answer and I or somebody else can answer it!

How to include [] in python regex code?

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]'.

Using python regex, find, and accessing groups

I'm using Python to (1) access an xml file, (2) search it for nodes containing regex1, (3) search the nodes found for regex2 (which has a couple capture groups), then (4) do things with the groups.
I've got steps 1 and 2 working. But I'm stuck on 3 and 4. Here's an example of my code:
from bs4 import BeautifulSoup
from urllib import urlopen
import re
from lxml import etree
url='https://www.gpo.gov/fdsys/bulkdata/BILLS/113/1/hr/BILLS-113hr2146ih.xml'
soup = BeautifulSoup(urlopen(url).read(), 'xml')
pattern = r'(am)(ed)'
regex = re.compile(pattern, re.IGNORECASE)
x = soup.find_all(text=re.compile("amended"))
count = 0
for each in x:
#I thought this would loop through x and search each result for
#the regex, then print the 2 groups like this: am--ed
print (regex.finditer(x[count]))
print (each.group(1), '--', each.group(2))
count = count + 1
But instead it prints this:
<callable-iterator object at 0x97efd0c>
Traceback (most recent call last):
File "/media/Windows/Documents and Settings/Andy/My Documents/Misc/Computer/Python/NLTK-Python Learning/test.py", line 17, in <module>
print (each.group(1), '--', each.group(2))
File "/usr/lib/python2.7/dist-packages/bs4/element.py", line 615, in __getattr__
self.__class__.__name__, attr))
AttributeError: 'NavigableString' object has no attribute 'group'
I've been playing with this for a week and have read everything relevant I can find online. But I'm obviously not understanding something. Any suggestions? - Thanks
Currently you aren't using your regex to search through each result of x. Try something like
for each in x:
for match in regex.finditer(each):
print (match.group(1), '--', match.group(2))

How to assert in django that F is only one time in ABCDEF

how do i assert that F appears only once in ABCDEF?
I used assertEqual but django states that:
Traceback (most recent call last):
File "/Users/jorrit/virtualenvs/voetbabbel/voetbabbel/apps/mass_mailer/tests.py", line 61, in test_create_mailing_list
self.assertContains(p.user.email,"#", 1, status_code=200)
File "/Library/Python/2.7/site-packages/django/test/testcases.py", line 419, in assertContains
self.assertEqual(response.status_code, status_code,
AttributeError: 'unicode' object has no attribute 'status_code'
and my code in the test:
self.assertContains(p.user.email,"#", 1)
assertContains is not for test random strings. It's for testing the response from view -- specifically that the response contains a certain bit of text. If you're not using a TestClient and testing against the response from one of your views, you can't use it.
Check out assertEqual. This is how the Django testing docs test for this sort of thing. Using assertEqual in this way will give you a little more feedback that assertTrue on failure.
self.assertEqual(p.user.email.count('#'), 1)
As Chris says, this isn't what assertContains is for. You can use one of the standard assertions:
self.assertTrue(p.user.email.count('#') == 1)