code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/env python # http://www.execommsys.com/VEC%20Professional%20Foot%20Pedals.htm # 05f3:00ff PI Engineering, Inc. signal_chars = [4, 12, 20] WORD_LENGTH = 24 def open_device(): hid_dev_index = 0 import sys if len(sys.argv) > 1: hid_dev_index = int(sys.argv[1]) hidfilename = "/dev/usb/hiddev%d" % (hid_dev_index) hidfile = None try: print "Attempting to open %s..." % hidfilename hidfile = open(hidfilename) except IOError: print "You need permission to access the device. Type the following:" print "sudo chmod a+r %s" % (hidfilename) exit(1) # Trick adopted from http://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python/1810703#1810703 # makes a non-blocking file import fcntl, os fd = hidfile.fileno() fl = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) return hidfile if __name__=="__main__": print "Depress pedal to test..." hidfile = open_device() prev_state = [0]*3 count = 0 while True: # XXX There was a problem (Issue 2) where the hidfile.read(WORD_LENGTH) line # froze. I reduced the read bytes to 1 (i.e. hidfile.read(1)), and found that # the read would only freeze at the first byte at the beginning of a message # after a previous message was complete. # The approach I took to solve this was to make the I/O nonbocking. # To reduce CPU consumption, I sleep when the buffer is not yet full. try: mystring = hidfile.read(WORD_LENGTH) except: import time time.sleep(0.05) continue print "="*40, "COUNT:", count, "="*40 print "Ord characters:", map(ord, mystring) buttons = [ord(mystring[i]) for i in signal_chars] print "Current state:", buttons, "Previous state:", prev_state prev_state = buttons count += 1 hidfile.close()
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def get_svn_config_dir(): """Return user's Subversion configuration directory.""" try: from win32com.shell.shell import SHGetFolderPath import win32com.shell.shellcon except ImportError: # If we can't import the win32api, just use ~; this is right on unix, and # returns not entirely unreasonable results on Windows. return os.path.expanduser('~/.subversion') # We're on Windows with win32api; use APPDATA. return os.path.join(SHGetFolderPath(0, win32com.shell.shellcon.CSIDL_APPDATA, 0, 0).encode('utf-8'), 'Subversion') def get_svn_auth(project_name, config_dir): """Return (username, password) for project_name in config_dir.""" # Default to returning nothing. result = (None, None) try: from svn.core import SVN_AUTH_CRED_SIMPLE, svn_config_read_auth_data from svn.core import SubversionException except ImportError: return result realm = ('<https://%s.googlecode.com:443> Google Code Subversion Repository' % project_name) # auth may be none even if no exception is raised, e.g. if config_dir does # not exist, or exists but has no entry for realm. try: auth = svn_config_read_auth_data(SVN_AUTH_CRED_SIMPLE, realm, config_dir) except SubversionException: auth = None if auth is not None: try: result = (auth['username'], auth['password']) except KeyError: # Missing the keys, so return nothing. pass return result def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, config_dir=None, user_name=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. If config_dir is None, try get_svn_config_dir(); if it is 'none', skip trying the Subversion configuration entirely. If user_name is not None, use it for the first attempt; prompt for subsequent attempts. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ if config_dir != 'none': # Try to load username/password from svn config for first try. if config_dir is None: config_dir = get_svn_config_dir() (svn_username, password) = get_svn_auth(project_name, config_dir) if user_name is None: # If username was not supplied by caller, use svn config. user_name = svn_username else: # Just initialize password for the first try. password = None while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('--config-dir', dest='config_dir', metavar='DIR', help='read svn auth data from DIR' ' ("none" means not to use svn auth data)') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-l', '--labels', dest='labels', help='An optional list of labels to attach to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.config_dir, options.user) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def get_svn_config_dir(): """Return user's Subversion configuration directory.""" try: from win32com.shell.shell import SHGetFolderPath import win32com.shell.shellcon except ImportError: # If we can't import the win32api, just use ~; this is right on unix, and # returns not entirely unreasonable results on Windows. return os.path.expanduser('~/.subversion') # We're on Windows with win32api; use APPDATA. return os.path.join(SHGetFolderPath(0, win32com.shell.shellcon.CSIDL_APPDATA, 0, 0).encode('utf-8'), 'Subversion') def get_svn_auth(project_name, config_dir): """Return (username, password) for project_name in config_dir.""" # Default to returning nothing. result = (None, None) try: from svn.core import SVN_AUTH_CRED_SIMPLE, svn_config_read_auth_data from svn.core import SubversionException except ImportError: return result realm = ('<https://%s.googlecode.com:443> Google Code Subversion Repository' % project_name) # auth may be none even if no exception is raised, e.g. if config_dir does # not exist, or exists but has no entry for realm. try: auth = svn_config_read_auth_data(SVN_AUTH_CRED_SIMPLE, realm, config_dir) except SubversionException: auth = None if auth is not None: try: result = (auth['username'], auth['password']) except KeyError: # Missing the keys, so return nothing. pass return result def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, config_dir=None, user_name=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. If config_dir is None, try get_svn_config_dir(); if it is 'none', skip trying the Subversion configuration entirely. If user_name is not None, use it for the first attempt; prompt for subsequent attempts. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ if config_dir != 'none': # Try to load username/password from svn config for first try. if config_dir is None: config_dir = get_svn_config_dir() (svn_username, password) = get_svn_auth(project_name, config_dir) if user_name is None: # If username was not supplied by caller, use svn config. user_name = svn_username else: # Just initialize password for the first try. password = None while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('--config-dir', dest='config_dir', metavar='DIR', help='read svn auth data from DIR' ' ("none" means not to use svn auth data)') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-l', '--labels', dest='labels', help='An optional list of labels to attach to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.config_dir, options.user) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
# main.py from google.appengine.ext import webapp from google.appengine.ext.webapp import RequestHandler from google.appengine.ext.webapp.util import run_wsgi_app from simple_login import SimpleLoginHandler from acct_lookup import AcctLookupHandler from unit_test import UnitTestHandler from create_contact import CreateContactHandler class RedirectToHomeHandler(RequestHandler): def get(self): self.redirect('/static/home.html') # # Main: # application = webapp.WSGIApplication([('/', RedirectToHomeHandler), ('/login', SimpleLoginHandler), ('/accountLookup', AcctLookupHandler), ('/createContact', CreateContactHandler), ('/unittest', UnitTestHandler) ], debug=True) run_wsgi_app(application)
Python
"""beatbox: Makes the salesforce.com SOAP API easily accessible.""" __version__ = "0.9" __author__ = "Simon Fell, Ron Hess" __credits__ = "Mad shouts to the sforce possie" __copyright__ = "(C) 2006 Simon Fell. GNU GPL 2." import sys from urlparse import urlparse from StringIO import StringIO import gzip import datetime import xmltramp import logging from xmltramp import islst from xml.sax.saxutils import XMLGenerator from xml.sax.saxutils import quoteattr from xml.sax.xmlreader import AttributesNSImpl from google.appengine.api import urlfetch # global constants for namespace strings, used during serialization _partnerNs = "urn:partner.soap.sforce.com" _sobjectNs = "urn:sobject.partner.soap.sforce.com" _envNs = "http://schemas.xmlsoap.org/soap/envelope/" _metadataNs = "http://soap.sforce.com/2006/04/metadata" _xsi = "http://www.w3.org/2001/XMLSchema-instance" _wsdl_apexNs = "http://soap.sforce.com/2006/08/apex" _noAttrs = AttributesNSImpl({}, {}) # global constants for xmltramp namespaces, used to access response data _tPartnerNS = xmltramp.Namespace(_partnerNs) _tSObjectNS = xmltramp.Namespace(_sobjectNs) _tMetadataNS = xmltramp.Namespace(_metadataNs) _tSoapNS = xmltramp.Namespace(_envNs) _tWsdlApexNS = xmltramp.Namespace(_wsdl_apexNs) _xmlns_attrs = AttributesNSImpl({ (None, u'xmlns'): _metadataNs}, {}) #(None, u'xmlns:ns2'): 'http://soap.sforce.com/2006/04/metadata' # global config gzipRequest=False # are we going to gzip the request ? gzipResponse=False # are we going to tell teh server to gzip the response ? forceHttp=False # force all connections to be HTTP, for debugging def makeConnection(scheme, host): try: if forceHttp or scheme.upper() == 'HTTP': return httplib.HTTPConnection(host) return httplib.HTTPSConnection(host) except NameError: pass # the main sforce client proxy class class Client: def __init__(self): self.batchSize = 500 self.serverUrl = "https://www.salesforce.com/services/Soap/u/14.0" self.__conn = None def __del__(self): if self.__conn != None: self.__conn.close() # login, the serverUrl and sessionId are automatically handled, returns the loginResult structure def login(self, username, password): lr = LoginRequest(self.serverUrl, username, password).post() self.useSession(str(lr[_tPartnerNS.sessionId]), str(lr[_tPartnerNS.serverUrl])) return lr def metalogin(self, username, password): lr = LoginRequest(self.serverUrl, username, password).post() self.useSession(str(lr[_tPartnerNS.sessionId]), str(lr[_tPartnerNS.metadataServerUrl])) return lr # initialize from an existing sessionId & serverUrl, useful if we're being launched via a custom link def useSession(self, sessionId, serverUrl): self.sessionId = sessionId self.__serverUrl = serverUrl (scheme, host, path, params, query, frag) = urlparse(self.__serverUrl) self.__conn = makeConnection(scheme, host) # set the batchSize property on the Client instance to change the batchsize for query/queryMore def query(self, soql): return QueryRequest(self.__serverUrl, self.sessionId, self.batchSize, soql).post(self.__conn) def queryMore(self, queryLocator): return QueryMoreRequest(self.__serverUrl, self.sessionId, self.batchSize, queryLocator).post(self.__conn) def getUpdated(self, sObjectType, start, end): return GetUpdatedRequest(self.__serverUrl, self.sessionId, sObjectType, start, end).post(self.__conn) def getDeleted(self, sObjectType, start, end): return GetDeletedRequest(self.__serverUrl, self.sessionId, sObjectType, start, end).post(self.__conn) def retrieve(self, fields, sObjectType, ids): return RetrieveRequest(self.__serverUrl, self.sessionId, fields, sObjectType, ids).post(self.__conn) # sObjects can be 1 or a list, returns a single save result or a list def create(self, sObjects): return CreateRequest(self.__serverUrl, self.sessionId, sObjects).post(self.__conn) def metacreate(self, metadata): return MetaCreateRequest(self.__serverUrl, self.sessionId, metadata).post(self.__conn) def checkstatus(self, id): return MetaCheckStatus(self.__serverUrl, self.sessionId, id).post(self.__conn) def metaupdate(self, metadata): return MetaUpdateRequest(self.__serverUrl, self.sessionId, metadata).post(self.__conn) # sObjects can be 1 or a list, returns a single save result or a list def update(self, sObjects): return UpdateRequest(self.__serverUrl, self.sessionId, sObjects).post(self.__conn) # sObjects can be 1 or a list, returns a single upsert result or a list def upsert(self, externalIdName, sObjects): return UpsertRequest(self.__serverUrl, self.sessionId, externalIdName, sObjects).post(self.__conn) # ids can be 1 or a list, returns a single delete result or a list def delete(self, ids): return DeleteRequest(self.__serverUrl, self.sessionId, ids).post(self.__conn) def executeanonymous(self, codeblock): return ExecuteAnnonRequest(self.__serverUrl, self.sessionId, codeblock).post(self.__conn) # sObjectTypes can be 1 or a list, returns a single describe result or a list of them def describeSObjects(self, sObjectTypes): return DescribeSObjectsRequest(self.__serverUrl, self.sessionId, sObjectTypes).post(self.__conn) def describeGlobal(self): return AuthenticatedRequest(self.__serverUrl, self.sessionId, "describeGlobal").post(self.__conn) def describeLayout(self, sObjectType): return DescribeLayoutRequest(self.__serverUrl, self.sessionId, sObjectType).post(self.__conn) def describeTabs(self): return AuthenticatedRequest(self.__serverUrl, self.sessionId, "describeTabs").post(self.__conn, True) def getServerTimestamp(self): return str(AuthenticatedRequest(self.__serverUrl, self.sessionId, "getServerTimestamp").post(self.__conn)[_tPartnerNS.timestamp]) def resetPassword(self, userId): return ResetPasswordRequest(self.__serverUrl, self.sessionId, userId).post(self.__conn) def setPassword(self, userId, password): SetPasswordRequest(self.__serverUrl, self.sessionId, userId, password).post(self.__conn) def getUserInfo(self): return AuthenticatedRequest(self.__serverUrl, self.sessionId, "getUserInfo").post(self.__conn) #def convertLead(self, convertLeads): # fixed version of XmlGenerator, handles unqualified attributes correctly class BeatBoxXmlGenerator(XMLGenerator): def __init__(self, destination, encoding): XMLGenerator.__init__(self, destination, encoding) def makeName(self, name): if name[0] is None: #if the name was not namespace-scoped, use the qualified part return name[1] # else try to restore the original prefix from the namespace return self._current_context[name[0]] + ":" + name[1] def startElementNS(self, name, qname, attrs): self._out.write('<' + self.makeName(name)) for pair in self._undeclared_ns_maps: self._out.write(' xmlns:%s="%s"' % pair) self._undeclared_ns_maps = [] for (name, value) in attrs.items(): self._out.write(' %s=%s' % (self.makeName(name), quoteattr(value))) self._out.write('>') # general purpose xml writer, does a bunch of useful stuff above & beyond XmlGenerator class XmlWriter: def __init__(self, doGzip): self.__buf = StringIO("") if doGzip: self.__gzip = gzip.GzipFile(mode='wb', fileobj=self.__buf) stm = self.__gzip else: stm = self.__buf self.__gzip = None self.xg = BeatBoxXmlGenerator(stm, "utf-8") self.xg.startDocument() self.__elems = [] def startPrefixMapping(self, prefix, namespace): self.xg.startPrefixMapping(prefix, namespace) def endPrefixMapping(self, prefix): self.xg.endPrefixMapping(prefix) def startElement(self, namespace, name, attrs = _noAttrs): self.xg.startElementNS((namespace, name), name, attrs) self.__elems.append((namespace, name)) # if value is a list, then it writes out repeating elements, one for each value def writeStringElement(self, namespace, name, value, attrs = _noAttrs): if islst(value): for v in value: self.writeStringElement(namespace, name, v, attrs) else: self.startElement(namespace, name, attrs) self.characters(value) self.endElement() def endElement(self): e = self.__elems[-1]; self.xg.endElementNS(e, e[1]) del self.__elems[-1] def characters(self, s): # todo base64 ? if isinstance(s, datetime.datetime): # todo, timezones s = s.isoformat() elif isinstance(s, datetime.date): # todo, try isoformat s = "%04d-%02d-%02d" % (s.year, s.month, s.day) elif isinstance(s, int): s = str(s) elif isinstance(s, float): s = str(s) self.xg.characters(s) def endDocument(self): self.xg.endDocument() if (self.__gzip != None): self.__gzip.close(); return self.__buf.getvalue() # exception class for soap faults class SoapFaultError(Exception): def __init__(self, faultCode, faultString): self.faultCode = faultCode self.faultString = faultString def __str__(self): return repr(self.faultCode) + " " + repr(self.faultString) class SessionTimeoutError(Exception): """SessionTimeouts are recoverable errors, merely needing the creation of a new connection, we create a new exception type, so these can be identified and handled seperately from SoapFaultErrors """ def __init__(self, faultCode, faultString): self.faultCode = faultCode self.faultString = faultString def __str__(self): return repr(self.faultCode) + " " + repr(self.faultString) # soap specific stuff ontop of XmlWriter class SoapWriter(XmlWriter): def __init__(self): XmlWriter.__init__(self, gzipRequest) self.startPrefixMapping("s", _envNs) self.startPrefixMapping("p", _partnerNs) self.startPrefixMapping("m", _metadataNs) self.startPrefixMapping("o", _sobjectNs) self.startPrefixMapping("w", _wsdl_apexNs) self.startPrefixMapping("xsi", _xsi) self.startElement(_envNs, "Envelope") def endDocument(self): self.endElement() # envelope self.endPrefixMapping("o") self.endPrefixMapping("p") self.endPrefixMapping("m") self.endPrefixMapping("s") self.endPrefixMapping("w") self.endPrefixMapping("xsi") return XmlWriter.endDocument(self) # processing for a single soap request / response class SoapEnvelope: def __init__(self, serverUrl, operationName, clientId="BeatBox/" + __version__, namespace=_partnerNs): self.serverUrl = serverUrl self.operationName = operationName self.clientId = clientId self.namespace = namespace self.meta = False def writeHeaders(self, writer): pass def writeBody(self, writer): pass def makeEnvelope(self): s = SoapWriter() s.startElement(_envNs, "Header") s.characters("\n") s.startElement(self.namespace , "CallOptions") s.writeStringElement(self.namespace , "client", self.clientId) s.endElement() s.characters("\n") self.writeHeaders(s) s.endElement() # Header s.startElement(_envNs, "Body") s.characters("\n") if ( self.meta ): s.startElement(None, self.operationName, _xmlns_attrs) else: s.startElement(self.namespace , self.operationName) self.writeBody(s) s.endElement() # operation s.endElement() # body return s.endDocument() # does all the grunt work, # serializes the request, # makes a http request, # passes the response to tramp # checks for soap fault # todo: check for mU='1' headers # returns the relevant result from the body child def post(self, conn=None, alwaysReturnList=False): headers = { "User-Agent": "BeatBox/" + __version__, "SOAPAction": "\"\"", "Content-Type": "text/xml; charset=utf-8" } if gzipResponse: headers['accept-encoding'] = 'gzip' if gzipRequest: headers['content-encoding'] = 'gzip' close = False (scheme, host, path, params, query, frag) = urlparse(self.serverUrl) max_attempts = 3 result = None attempt = 1 logging.info(self.serverUrl) logging.info(self.makeEnvelope()) while not result and attempt <= max_attempts: #try: result = urlfetch.fetch(self.serverUrl, self.makeEnvelope(), urlfetch.POST, headers); rawResponse = result.content #except: # result = None # attempt += 1 #if not result: # logging.info(sys.exc_info()); # raise 'No response from Salesforce' # logging.info(result.headers); if result.headers.has_key('content-encoding') and result.headers['content-encoding'] == 'gzip': rawResponse = gzip.GzipFile(fileobj=StringIO(rawResponse)).read() # slow? # logging.info(rawResponse) tramp = xmltramp.parse(rawResponse) try: faultString = str(tramp[_tSoapNS.Body][_tSoapNS.Fault].faultstring) faultCode = str(tramp[_tSoapNS.Body][_tSoapNS.Fault].faultcode).split(':')[-1] if faultCode == 'INVALID_SESSION_ID': raise SessionTimeoutError(faultCode, faultString) else: raise SoapFaultError(faultCode, faultString) except KeyError: pass # first child of body is XXXXResponse result = tramp[_tSoapNS.Body][0] # it contains either a single child, or for a batch call multiple children if alwaysReturnList or len(result) > 1: return result[:] else: return result[0] class LoginRequest(SoapEnvelope): def __init__(self, serverUrl, username, password): SoapEnvelope.__init__(self, serverUrl, "login") self.__username = username self.__password = password def writeBody(self, s): s.writeStringElement(_partnerNs, "username", self.__username) s.writeStringElement(_partnerNs, "password", self.__password) # base class for all methods that require a sessionId class AuthenticatedRequest(SoapEnvelope): def __init__(self, serverUrl, sessionId, operationName): SoapEnvelope.__init__(self, serverUrl, operationName) self.sessionId = sessionId def writeHeaders(self, s): s.startElement(self.namespace, "SessionHeader") s.writeStringElement(self.namespace, "sessionId", self.sessionId) s.endElement() def writeSObjects(self, s, sObjects, elemName="sObjects"): if islst(sObjects): for o in sObjects: self.writeSObjects(s, o, elemName) else: s.startElement(_partnerNs, elemName) # type has to go first s.writeStringElement(_sobjectNs, "type", sObjects['type']) for fn in sObjects.keys(): if (fn != 'type'): s.writeStringElement(_sobjectNs, fn, sObjects[fn]) s.endElement() # for Meta data apply a different namespace class MetaCreateRequest(AuthenticatedRequest): def __init__(self, serverUrl, sessionId, metadata, operationName="create"): logging.info(serverUrl) AuthenticatedRequest.__init__(self, serverUrl, sessionId, operationName) self.__metadata = metadata self.meta = True self.namespace = _metadataNs def writeBody(self, s): attr_vals = { (None, u'xsi:type'): 'ns2:'+ self.__metadata['xsitype'], (None, u'xmlns:ns2'): _metadataNs } s.startElement(None, "metadata", AttributesNSImpl(attr_vals, { }) ) s.characters("\n") for fn in self.__metadata: if ( fn == 'xsitype' ): pass elif ( fn == 'nameField' ): s.startElement(None,'nameField') nameField = self.__metadata[fn]; logging.info(nameField) for nf in nameField: s.writeStringElement(None, nf, nameField[nf]) s.endElement() # name field elif (fn == 'tabVisibilities'): s.startElement(None,'tabVisibilities') tabVisibilities = self.__metadata[fn]; logging.info(tabVisibilities) for nf in tabVisibilities: s.writeStringElement(None, nf, tabVisibilities[nf]) s.endElement() else : s.writeStringElement(None, fn, self.__metadata[fn]) s.characters("\n") s.endElement() # metadata class MetaUpdateRequest(AuthenticatedRequest): def __init__(self, serverUrl, sessionId, metadata, operationName="update"): logging.info(serverUrl) AuthenticatedRequest.__init__(self, serverUrl, sessionId, operationName) self.__metadata = metadata self.meta = True self.namespace = _metadataNs self.currentName = metadata['fullName'] def writeBody(self, s): attr_vals = { (None, u'xsi:type'): 'ns2:'+ self.__metadata['xsitype'], (None, u'xmlns:ns2'): _metadataNs } s.startElement(None, 'UpdateMetadata' ) s.writeStringElement(None, 'currentName', self.currentName) s.startElement(None, "metadata", AttributesNSImpl(attr_vals, { }) ) s.characters("\n") for fn in self.__metadata: if ( fn == 'xsitype' ): pass elif ( fn == 'nameField' ): s.startElement(None,'nameField') nameField = self.__metadata[fn]; logging.info(nameField) for nf in nameField: s.writeStringElement(None, nf, nameField[nf]) s.endElement() # name field elif (fn == 'tabVisibilities'): s.startElement(None,'tabVisibilities') tabVisibilities = self.__metadata[fn]; logging.info(tabVisibilities) for nf in tabVisibilities: s.writeStringElement(None, nf, tabVisibilities[nf]) s.endElement() else : s.writeStringElement(None, fn, self.__metadata[fn]) s.characters("\n") s.endElement() # updateMetadata s.endElement() # metadata class MetaCheckStatus(AuthenticatedRequest): def __init__(self, serverUrl, sessionId, id): AuthenticatedRequest.__init__(self, serverUrl, sessionId, 'checkStatus' ) self.__id = id self.meta = True self.namespace = _metadataNs def writeBody(self, s): s.writeStringElement(None, 'id', self.__id) class QueryOptionsRequest(AuthenticatedRequest): def __init__(self, serverUrl, sessionId, batchSize, operationName): AuthenticatedRequest.__init__(self, serverUrl, sessionId, operationName) self.batchSize = batchSize def writeHeaders(self, s): AuthenticatedRequest.writeHeaders(self, s) s.startElement(_partnerNs, "QueryOptions") s.writeStringElement(_partnerNs, "batchSize", self.batchSize) s.endElement() class QueryRequest(QueryOptionsRequest): def __init__(self, serverUrl, sessionId, batchSize, soql): QueryOptionsRequest.__init__(self, serverUrl, sessionId, batchSize, "query") self.__query = soql def writeBody(self, s): s.writeStringElement(_partnerNs, "queryString", self.__query) class QueryMoreRequest(QueryOptionsRequest): def __init__(self, serverUrl, sessionId, batchSize, queryLocator): QueryOptionsRequest.__init__(self, serverUrl, sessionId, batchSize, "queryMore") self.__queryLocator = queryLocator def writeBody(self, s): s.writeStringElement(_partnerNs, "queryLocator", self.__queryLocator) class GetUpdatedRequest(AuthenticatedRequest): def __init__(self, serverUrl, sessionId, sObjectType, start, end, operationName="getUpdated"): AuthenticatedRequest.__init__(self, serverUrl, sessionId, operationName) self.__sObjectType = sObjectType self.__start = start; self.__end = end; def writeBody(self, s): s.writeStringElement(_partnerNs, "sObjectType", self.__sObjectType) s.writeStringElement(_partnerNs, "startDate", self.__start) s.writeStringElement(_partnerNs, "endDate", self.__end) class GetDeletedRequest(GetUpdatedRequest): def __init__(self, serverUrl, sessionId, sObjectType, start, end): GetUpdatedRequest.__init__(self, serverUrl, sessionId, sObjectType, start, end, "getDeleted") class UpsertRequest(AuthenticatedRequest): def __init__(self, serverUrl, sessionId, externalIdName, sObjects): AuthenticatedRequest.__init__(self, serverUrl, sessionId, "upsert") self.__externalIdName = externalIdName self.__sObjects = sObjects def writeBody(self, s): s.writeStringElement(_partnerNs, "externalIDFieldName", self.__externalIdName) self.writeSObjects(s, self.__sObjects) class UpdateRequest(AuthenticatedRequest): def __init__(self, serverUrl, sessionId, sObjects, operationName="update"): AuthenticatedRequest.__init__(self, serverUrl, sessionId, operationName) self.__sObjects = sObjects def writeBody(self, s): self.writeSObjects(s, self.__sObjects) class CreateRequest(UpdateRequest): def __init__(self, serverUrl, sessionId, sObjects): UpdateRequest.__init__(self, serverUrl, sessionId, sObjects, "create") class ExecuteAnnonRequest(AuthenticatedRequest): def __init__(self, serverUrl, sessionId, codeblock): serverUrl = serverUrl.replace('/u/','/s/') AuthenticatedRequest.__init__(self, serverUrl, sessionId, "executeAnonymous") self.__block = codeblock; self.namespace = _wsdl_apexNs def writeBody(self, s): s.writeStringElement(_wsdl_apexNs, "String", self.__block) class DeleteRequest(AuthenticatedRequest): def __init__(self, serverUrl, sessionId, ids): AuthenticatedRequest.__init__(self, serverUrl, sessionId, "delete") self.__ids = ids; def writeBody(self, s): s.writeStringElement(_partnerNs, "id", self.__ids) class RetrieveRequest(AuthenticatedRequest): def __init__(self, serverUrl, sessionId, fields, sObjectType, ids): AuthenticatedRequest.__init__(self, serverUrl, sessionId, "retrieve") self.__fields = fields self.__sObjectType = sObjectType self.__ids = ids def writeBody(self, s): s.writeStringElement(_partnerNs, "fieldList", self.__fields) s.writeStringElement(_partnerNs, "sObjectType", self.__sObjectType); s.writeStringElement(_partnerNs, "ids", self.__ids) class ResetPasswordRequest(AuthenticatedRequest): def __init__(self, serverUrl, sessionId, userId): AuthenticatedRequest.__init__(self, serverUrl, sessionId, "resetPassword") self.__userId = userId def writeBody(self, s): s.writeStringElement(_partnerNs, "userId", self.__userId) class SetPasswordRequest(AuthenticatedRequest): def __init__(self, serverUrl, sessionId, userId, password): AuthenticatedRequest.__init__(self, serverUrl, sessionId, "setPassword") self.__userId = userId self.__password = password def writeBody(self, s): s.writeStringElement(_partnerNs, "userId", self.__userId) s.writeStringElement(_partnerNs, "password", self.__password) class DescribeSObjectsRequest(AuthenticatedRequest): def __init__(self, serverUrl, sessionId, sObjectTypes): AuthenticatedRequest.__init__(self, serverUrl, sessionId, "describeSObjects") self.__sObjectTypes = sObjectTypes def writeBody(self, s): s.writeStringElement(_partnerNs, "sObjectType", self.__sObjectTypes) class DescribeLayoutRequest(AuthenticatedRequest): def __init__(self, serverUrl, sessionId, sObjectType): AuthenticatedRequest.__init__(self, serverUrl, sessionId, "describeLayout") self.__sObjectType = sObjectType def writeBody(self, s): s.writeStringElement(_partnerNs, "sObjectType", self.__sObjectType)
Python
from _beatbox import _tPartnerNS, _tSObjectNS, _tSoapNS from _beatbox import Client as BaseClient from marshall import marshall from types import TupleType, ListType import re import copy from xmltramp import Namespace, Element import sys import logging import pickle _tSchemaInstanceNS = Namespace('http://www.w3.org/2001/XMLSchema-instance') _tSchemaNS = Namespace('http://www.w3.org/2001/XMLSchema') _tMetadataNS = Namespace('http://soap.sforce.com/2006/04/metadata') querytyperegx = re.compile('(?:from|FROM) (\S+)') class SObject(object): def __init__(self, **kw): for k, v in kw.items(): #print ' init sobject ' + k + ' ' + str(v) setattr(self, k, v) def marshall(self, fieldname, xml): field = self.fields[fieldname] return field.marshall(xml) def get(self, key): return self.__dict__.get(key) def __getitem__(self, key): return self.__dict__.get(key) def keys(self): return self.__dict__.keys() class Client(BaseClient): # def __init__(self): # self.describeCache = dict() def login(self, username, passwd): res = BaseClient.login(self, username, passwd) data = dict() data['passwordExpired'] = _bool(res[_tPartnerNS.passwordExpired]) data['serverUrl'] = str(res[_tPartnerNS.serverUrl]) data['sessionId'] = str(res[_tPartnerNS.sessionId]) data['userId'] = str(res[_tPartnerNS.userId]) data['metadataServerUrl'] = str(res[_tPartnerNS.metadataServerUrl]) data['userInfo'] = _extractUserInfo(res[_tPartnerNS.userInfo]) self.describeCache = dict() return data def useSession(self, sessionId, serverUrl): if ( str(sessionId) == '' or str(serverUrl) == '' ): raise AttributeError , 'Missing server url or session ID to useSession method' logging.info( sessionId, serverUrl) res = BaseClient.useSession(self, sessionId, serverUrl) #print res.__dict__ data = dict() # data['passwordExpired'] = _bool(res[_tPartnerNS.passwordExpired]) # data['serverUrl'] = str(res[_tPartnerNS.serverUrl]) # data['sessionId'] = str(res[_tPartnerNS.sessionId]) # data['userId'] = str(res[_tPartnerNS.userId]) # data['userInfo'] = _extractUserInfo(res[_tPartnerNS.userInfo]) self.describeCache = dict() return self.getUserInfo() def isConnected(self): """ First pass at a method to check if we're connected or not """ if self.__conn and self.__conn._HTTPConnection__state == 'Idle': return True return False def describeGlobal(self): res = BaseClient.describeGlobal(self) data = dict() data['encoding'] = str(res[_tPartnerNS.encoding]) data['maxBatchSize'] = int(str(res[_tPartnerNS.maxBatchSize])) data['types'] = [str(t) for t in res[_tPartnerNS.types:]] return data def describeSObjects(self, sObjectTypes): if (self.describeCache.has_key(sObjectTypes)): data = list() data.append(self.describeCache[sObjectTypes]) return data res = BaseClient.describeSObjects(self, sObjectTypes) if type(res) not in (TupleType, ListType): res = [res] data = list() for r in res: d = dict() d['activateable'] = _bool(r[_tPartnerNS.activateable]) d['createable'] = _bool(r[_tPartnerNS.createable]) d['custom'] = _bool(r[_tPartnerNS.custom]) d['deletable'] = _bool(r[_tPartnerNS.deletable]) fields = r[_tPartnerNS.fields:] fields = [_extractFieldInfo(f) for f in fields] field_map = dict() for f in fields: field_map[f.name] = f d['fields'] = field_map rawreldata = r[_tPartnerNS.ChildRelationships:] # why is this list empty ? # print repr(rawreldata) relinfo = [_extractChildRelInfo(cr) for cr in rawreldata] d['ChildRelationships'] = relinfo d['keyPrefix'] = str(r[_tPartnerNS.keyPrefix]) d['label'] = str(r[_tPartnerNS.label]) d['labelPlural'] = str(r[_tPartnerNS.labelPlural]) d['layoutable'] = _bool(r[_tPartnerNS.layoutable]) d['name'] = str(r[_tPartnerNS.name]) d['queryable'] = _bool(r[_tPartnerNS.queryable]) d['replicateable'] = _bool(r[_tPartnerNS.replicateable]) d['retrieveable'] = _bool(r[_tPartnerNS.retrieveable]) d['searchable'] = _bool(r[_tPartnerNS.searchable]) d['undeletable'] = _bool(r[_tPartnerNS.undeletable]) d['updateable'] = _bool(r[_tPartnerNS.updateable]) d['urlDetail'] = str(r[_tPartnerNS.urlDetail]) d['urlEdit'] = str(r[_tPartnerNS.urlEdit]) d['urlNew'] = str(r[_tPartnerNS.urlNew]) data.append(SObject(**d)) self.describeCache[str(r[_tPartnerNS.name])] = SObject(**d) return data def create(self, sObjects): preparedObjects = _prepareSObjects(sObjects) res = BaseClient.create(self, preparedObjects) if type(res) not in (TupleType, ListType): res = [res] data = list() for r in res: d = dict() data.append(d) d['id'] = str(r[_tPartnerNS.id]) d['success'] = success = _bool(r[_tPartnerNS.success]) if not success: d['errors'] = [_extractError(e) for e in r[_tPartnerNS.errors:]] else: d['errors'] = list() return data def retrieve(self, fields, sObjectType, ids): resultSet = BaseClient.retrieve(self, fields, sObjectType, ids) type_data = self.describeSObjects(sObjectType)[0] if type(resultSet) not in (TupleType, ListType): if isnil(resultSet): resultSet = list() else: resultSet = [resultSet] fields = [f.strip() for f in fields.split(',')] data = list() for result in resultSet: d = dict() data.append(d) for fname in fields: d[fname] = type_data.marshall(fname, result) return data def update(self, sObjects): preparedObjects = _prepareSObjects(sObjects) res = BaseClient.update(self, preparedObjects) if type(res) not in (TupleType, ListType): res = [res] data = list() for r in res: d = dict() data.append(d) d['id'] = str(r[_tPartnerNS.id]) d['success'] = success = _bool(r[_tPartnerNS.success]) if not success: d['errors'] = [_extractError(e) for e in r[_tPartnerNS.errors:]] else: d['errors'] = list() return data def query_old(self, fields, sObjectType, conditionExpression=''): #type_data = self.describeSObjects(sObjectType)[0] queryString = 'select %s from %s' % (fields, sObjectType) if conditionExpression: queryString = '%s where %s' % (queryString, conditionExpression) fields = [f.strip() for f in fields.split(',')] res = BaseClient.query(self, queryString) locator = QueryLocator( str(res[_tPartnerNS.queryLocator]), ) data = dict(queryLocator = locator, done = _bool(res[_tPartnerNS.done]), records = [self.extractRecord( r ) for r in res[_tPartnerNS.records:]], size = int(str(res[_tPartnerNS.size])) ) return data def extractRecord(self, r): def sobjectType(r): """ find the type of sobject given a query result""" for x in r._dir: if isinstance(x, Element) : if ( x._name == _tSObjectNS.type): return x._dir[0] raise AttributeError, 'No Sobject element type found' def fieldsList(r): """ list all the field names in this record, skip type as this is special, and does not get marshaled""" ret= list() for field in r: f = str(field._name[1:][0]) if ( f != 'type' ) : ret.append(f) return ret def getFieldByName(fname, r): """ from this record, locate a child by name""" for fld in r: if ( fld._name[1] == fname ) : return fld raise KeyError, 'could not locate '+fname+ ' in record' # begin the extract of information sObjectType = sobjectType(r) #print 'sobject type is : ' + sObjectType type_data = self.describeSObjects(sObjectType)[0] data = dict() data['type'] = sObjectType myfields = fieldsList(r) for fname in myfields: try : data[fname] = type_data.marshall(fname, r) except KeyError : # no key of this type, perhaps this is a query result # from a related list returned from the server fld = getFieldByName(fname, r) if ( len(fld) == 0 ): # load a null related list data[fname] = dict(queryLocator = None, done = True, records = [], size = int(0) ) continue if ( str(fld(_tSchemaInstanceNS.type)) != 'QueryResult' ) : raise AttributeError, 'Expected QueryResult or Field' # load the populated related list data[fname] = dict(queryLocator = None, done = True, records = [self.extractRecord(p) for p in fld[_tPartnerNS.records:]], size = int(str(fld[_tPartnerNS.size])) ) #print str(data) return data def query(self, queryString): res = BaseClient.query(self, queryString) locator = QueryLocator( str(res[_tPartnerNS.queryLocator]) ) data = dict(queryLocator = locator, done = _bool(res[_tPartnerNS.done]), records = [self.extractRecord( r ) for r in res[_tPartnerNS.records:]], size = int(str(res[_tPartnerNS.size])) ) return data def queryMore(self, queryLocator): locator = queryLocator.locator #sObjectType = queryLocator.sObjectType #fields = queryLocator.fields res = BaseClient.queryMore(self, locator) locator = QueryLocator( str(res[_tPartnerNS.queryLocator]) ) data = dict(queryLocator = locator, done = _bool(res[_tPartnerNS.done]), records = [self.extractRecord( r ) for r in res[_tPartnerNS.records:]], size = int(str(res[_tPartnerNS.size])) ) return data def delete(self, ids): res = BaseClient.delete(self, ids) if type(res) not in (TupleType, ListType): res = [res] data = list() for r in res: d = dict() data.append(d) d['id'] = str(r[_tPartnerNS.id]) d['success'] = success = _bool(r[_tPartnerNS.success]) if not success: d['errors'] = [_extractError(e) for e in r[_tPartnerNS.errors:]] else: d['errors'] = list() return data def upsert(self, externalIdName, sObjects): preparedObjects = _prepareSObjects(sObjects) res = BaseClient.upsert(self, externalIdName, preparedObjects) if type(res) not in (TupleType, ListType): res = [res] data = list() for r in res: d = dict() data.append(d) d['id'] = str(r[_tPartnerNS.id]) d['success'] = success = _bool(r[_tPartnerNS.success]) if not success: d['errors'] = [_extractError(e) for e in r[_tPartnerNS.errors:]] else: d['errors'] = list() d['isCreated'] = _bool(r[_tPartnerNS.isCreated]) return data def getDeleted(self, sObjectType, start, end): res = BaseClient.getDeleted(self, sObjectType, start, end) res = res[_tPartnerNS.deletedRecords:] if type(res) not in (TupleType, ListType): res = [res] data = list() for r in res: d = dict( id = str(r[_tPartnerNS.id]), deletedDate = marshall('datetime', 'deletedDate', r, ns=_tPartnerNS)) data.append(d) return data def getUpdated(self, sObjectType, start, end): res = BaseClient.getUpdated(self, sObjectType, start, end) res = res[_tPartnerNS.ids:] if type(res) not in (TupleType, ListType): res = [res] return [str(r) for r in res] def getUserInfo(self): res = BaseClient.getUserInfo(self) data = _extractUserInfo(res) return data def executeanonymous(self, code): res = BaseClient.executeanonymous(self, code) data = dict() logging.info( res ) return data def describeTabs(self): res = BaseClient.describeTabs(self) data = list() for r in res: tabs = [_extractTab(t) for t in r[_tPartnerNS.tabs:]] d = dict( label = str(r[_tPartnerNS.label]), logoUrl = str(r[_tPartnerNS.logoUrl]), selected = _bool(r[_tPartnerNS.selected]), tabs=tabs) return data def describeLayout(self, sObjectType): raise NotImplementedError class MetaClient(Client): def __init__(self): self.serverUrl = "https://www.salesforce.com/services/Soap/u/13.0" def login(self, username, passwd): res = BaseClient.metalogin(self, username, passwd) logging.info(self.serverUrl) data = dict() data['passwordExpired'] = _bool(res[_tPartnerNS.passwordExpired]) data['metadataServerUrl'] = str(res[_tPartnerNS.metadataServerUrl]) data['sessionId'] = str(res[_tPartnerNS.sessionId]) data['userId'] = str(res[_tPartnerNS.userId]) data['userInfo'] = _extractUserInfo(res[_tPartnerNS.userInfo]) return data def useSession(self, sessionId, serverUrl): if ( str(sessionId) == '' or str(serverUrl) == '' ): raise AttributeError , 'Missing server url or session ID to useSession method' logging.info( sessionId, serverUrl) res = BaseClient.useSession(self, sessionId, serverUrl) data = dict() data['sessionId'] = sessionId return data def metaupdate(self, metadata): res = BaseClient.metaupdate(self, metadata) return _extractAsyncResult(res) def metacreate(self, metadata): res = BaseClient.metacreate(self, metadata) return _extractAsyncResult(res) def checkstatus(self, id): res = BaseClient.checkstatus(self, id) return _extractAsyncResult(res) def _extractAsyncResult(res): data = dict() data['done'] = _bool(res[_tMetadataNS.done]); data['id'] = str(res[_tMetadataNS.id]); data['state'] = str(res[_tMetadataNS.state]); data['secondsToWait'] = str(res[_tMetadataNS.secondsToWait]); try: data['statusCode'] = str(res[_tMetadataNS.statusCode]); data['message'] = str(res[_tMetadataNS.message]); except: data['statusCode'] = '0' logging.info( data ) return data class QueryLocator(object): def __init__(self, locator): self.locator = locator class Field(object): def __init__(self, **kw): for k,v in kw.items(): setattr(self, k, v) def marshall(self, xml): return marshall(self.type, self.name, xml) # sObjects can be 1 or a list. If values are python lists or tuples, we # convert these to strings: # ['one','two','three'] becomes 'one;two;three' def _prepareSObjects(sObjects): def _doPrep(field_dict): """Salesforce expects string to be "apple;orange;pear" so if a field is in Python list format, convert it to string. We also set an array of any list-type fields that should be set to empty, as this is a special case in the Saleforce API, and merely setting the list to an empty string doesn't cause the values to be updated.""" fieldsToNull = [] for k,v in field_dict.items(): if hasattr(v,'__iter__'): if len(v) == 0: fieldsToNull.append(k) else: field_dict[k] = ";".join(v) field_dict['fieldsToNull'] = fieldsToNull sObjectsCopy = copy.deepcopy(sObjects) if isinstance(sObjectsCopy,dict): _doPrep(sObjectsCopy) else: for listitems in sObjectsCopy: _doPrep(listitems) return sObjectsCopy def _bool(val): return str(val) == 'true' def _extractFieldInfo(fdata): data = dict() data['autoNumber'] = _bool(fdata[_tPartnerNS.autoNumber]) data['byteLength'] = int(str(fdata[_tPartnerNS.byteLength])) data['calculated'] = _bool(fdata[_tPartnerNS.calculated]) data['createable'] = _bool(fdata[_tPartnerNS.createable]) data['nillable'] = _bool(fdata[_tPartnerNS.nillable]) data['custom'] = _bool(fdata[_tPartnerNS.custom]) data['defaultedOnCreate'] = _bool(fdata[_tPartnerNS.defaultedOnCreate]) data['digits'] = int(str(fdata[_tPartnerNS.digits])) data['filterable'] = _bool(fdata[_tPartnerNS.filterable]) try: data['htmlFormatted'] = _bool(fdata[_tPartnerNS.htmlFormatted]) except KeyError: data['htmlFormatted'] = False data['label'] = str(fdata[_tPartnerNS.label]) data['length'] = int(str(fdata[_tPartnerNS.length])) data['name'] = str(fdata[_tPartnerNS.name]) data['nameField'] = _bool(fdata[_tPartnerNS.nameField]) plValues = fdata[_tPartnerNS.picklistValues:] data['picklistValues'] = [_extractPicklistEntry(p) for p in plValues] data['precision'] = int(str(fdata[_tPartnerNS.precision])) data['referenceTo'] = [str(r) for r in fdata[_tPartnerNS.referenceTo:]] data['restrictedPicklist'] = _bool(fdata[_tPartnerNS.restrictedPicklist]) data['scale'] = int(str(fdata[_tPartnerNS.scale])) data['soapType'] = str(fdata[_tPartnerNS.soapType]) data['type'] = str(fdata[_tPartnerNS.type]) data['updateable'] = _bool(fdata[_tPartnerNS.updateable]) try: data['dependentPicklist'] = _bool(fdata[_tPartnerNS.dependentPicklist]) data['controllerName'] = str(fdata[_tPartnerNS.controllerName]) except KeyError: data['dependentPicklist'] = False data['controllerName'] = '' return Field(**data) def _extractPicklistEntry(pldata): data = dict() data['active'] = _bool(pldata[_tPartnerNS.active]) data['validFor'] = [str(v) for v in pldata[_tPartnerNS.validFor:]] data['defaultValue'] = _bool(pldata[_tPartnerNS.defaultValue]) data['label'] = str(pldata[_tPartnerNS.label]) data['value'] = str(pldata[_tPartnerNS.value]) return data def _extractChildRelInfo(crdata): data = dict() data['cascadeDelete'] = _bool(rel[_tPartnerNS.cascadeDelete]) data['childSObject'] = str(rel[_tPartnerNS.childSObject]) data['field'] = str(rel[_tPartnerNS.field]) return data def _extractError(edata): data = dict() data['statusCode'] = str(edata[_tPartnerNS.statusCode]) data['message'] = str(edata[_tPartnerNS.message]) data['fields'] = [str(f) for f in edata[_tPartnerNS.fields:]] return data def _extractTab(tdata): data = dict( custom = _bool(tdata[_tPartnerNS.custom]), label = str(tdata[_tPartnerNS.label]), sObjectName = str(tdata[_tPartnerNS.sobjectName]), url = str(tdata[_tPartnerNS.url])) return data def _extractUserInfo(res): data = dict( accessibilityMode = _bool(res[_tPartnerNS.accessibilityMode]), currencySymbol = str(res[_tPartnerNS.currencySymbol]), organizationId = str(res[_tPartnerNS.organizationId]), organizationMultiCurrency = _bool( res[_tPartnerNS.organizationMultiCurrency]), organizationName = str(res[_tPartnerNS.organizationName]), userDefaultCurrencyIsoCode = str( res[_tPartnerNS.userDefaultCurrencyIsoCode]), userEmail = str(res[_tPartnerNS.userEmail]), userFullName = str(res[_tPartnerNS.userFullName]), userId = str(res[_tPartnerNS.userId]), userLanguage = str(res[_tPartnerNS.userLanguage]), userLocale = str(res[_tPartnerNS.userLocale]), userTimeZone = str(res[_tPartnerNS.userTimeZone]), userUiSkin = str(res[_tPartnerNS.userUiSkin])) return data def isnil(xml): try: if xml(_tSchemaInstanceNS.nil) == 'true': return True else: return False except KeyError: return False
Python
from _beatbox import _tPartnerNS, _tSObjectNS, _tSoapNS import python_client from types import ListType, TupleType import datetime, re dateregx = re.compile(r'(\d{4})-(\d{2})-(\d{2})') datetimeregx = re.compile( r'(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)(.*)') doubleregx = re.compile(r'^(\d)+(\.\d+)?$') stringtypes = ('string', 'id', 'textarea', 'phone', 'url', 'email', 'anyType', 'picklist', 'reference') doubletypes = ('double', 'currency', 'percent') multitypes = ('combobox', 'multipicklist') _marshallers = dict() def marshall(fieldtype, fieldname, xml, ns=_tSObjectNS): m = _marshallers[fieldtype] return m(fieldname, xml, ns) def register(fieldtypes, func): if type(fieldtypes) not in (ListType, TupleType): fieldtypes = [fieldtypes] for t in fieldtypes: _marshallers[t] = func def stringMarshaller(fieldname, xml, ns): return str(xml[getattr(ns,fieldname)]) register(stringtypes, stringMarshaller) def multiMarshaller(fieldname, xml, ns): asString = str(xml[getattr(ns,fieldname):][0]) if not asString: return [] return asString.split(';') register(multitypes, multiMarshaller) def booleanMarshaller(fieldname, xml, ns): return python_client._bool(xml[getattr(ns,fieldname)]) register('boolean', booleanMarshaller) def integerMarshaller(fieldname, xml, ns): strVal = str(xml[getattr(ns,fieldname)]) try: i = int(strVal) return i except: return None register('int', integerMarshaller) def doubleMarshaller(fieldname, xml, ns): strVal = str(xml[getattr(ns,fieldname)]) try: i = float(strVal) return i except: return None register(doubletypes, doubleMarshaller) def dateMarshaller(fieldname, xml, ns): datestr = str(xml[getattr(ns,fieldname)]) match = dateregx.match(datestr) if match: grps = match.groups() year = int(grps[0]) month = int(grps[1]) day = int(grps[2]) return datetime.date(year, month, day) return None register('date', dateMarshaller) def dateTimeMarshaller(fieldname, xml, ns): datetimestr = str(xml[getattr(ns,fieldname)]) match = datetimeregx.match(datetimestr) if match: grps = match.groups() year = int(grps[0]) month = int(grps[1]) day = int(grps[2]) hour = int(grps[3]) minute = int(grps[4]) second = int(grps[5]) secfrac = float(grps[6]) microsecond = int(secfrac * (10**6)) tz = grps[7] # XXX not sure if I need to do anything with this. sofar # times appear to be UTC return datetime.datetime(year, month, day, hour, minute, second, microsecond) return None register('datetime', dateTimeMarshaller) def base64Marshaller(fieldname, xml, ns): return str(xml[getattr(ns,fieldname)]) register('base64', base64Marshaller)
Python
"""xmltramp: Make XML documents easily accessible.""" __version__ = "2.16" __author__ = "Aaron Swartz" __credits__ = "Many thanks to pjz, bitsko, and DanC." __copyright__ = "(C) 2003 Aaron Swartz. GNU GPL 2." if not hasattr(__builtins__, 'True'): True, False = 1, 0 def isstr(f): return isinstance(f, type('')) or isinstance(f, type(u'')) def islst(f): return isinstance(f, type(())) or isinstance(f, type([])) empty = {'http://www.w3.org/1999/xhtml': ['img', 'br', 'hr', 'meta', 'link', 'base', 'param', 'input', 'col', 'area']} def quote(x, elt=True): if elt and '<' in x and len(x) > 24 and x.find(']]>') == -1: return "<![CDATA["+x+"]]>" else: x = x.replace('&', '&amp;').replace('<', '&lt;').replace(']]>', ']]&gt;') if not elt: x = x.replace('"', '&quot;') return x class Element: def __init__(self, name, attrs=None, children=None, prefixes=None): if islst(name) and name[0] == None: name = name[1] if attrs: na = {} for k in attrs.keys(): if islst(k) and k[0] == None: na[k[1]] = attrs[k] else: na[k] = attrs[k] attrs = na self._name = name self._attrs = attrs or {} self._dir = children or [] prefixes = prefixes or {} self._prefixes = dict(zip(prefixes.values(), prefixes.keys())) if prefixes: self._dNS = prefixes.get(None, None) else: self._dNS = None def __repr__(self, recursive=0, multiline=0, inprefixes=None): def qname(name, inprefixes): if islst(name): if inprefixes[name[0]] is not None: return inprefixes[name[0]]+':'+name[1] else: return name[1] else: return name def arep(a, inprefixes, addns=1): out = '' for p in self._prefixes.keys(): if not p in inprefixes.keys(): if addns: out += ' xmlns' if addns and self._prefixes[p]: out += ':'+self._prefixes[p] if addns: out += '="'+quote(p, False)+'"' inprefixes[p] = self._prefixes[p] for k in a.keys(): out += ' ' + qname(k, inprefixes)+ '="' + quote(a[k], False) + '"' return out inprefixes = inprefixes or {u'http://www.w3.org/XML/1998/namespace':'xml'} # need to call first to set inprefixes: attributes = arep(self._attrs, inprefixes, recursive) out = '<' + qname(self._name, inprefixes) + attributes if not self._dir and (self._name[0] in empty.keys() and self._name[1] in empty[self._name[0]]): out += ' />' return out out += '>' if recursive: content = 0 for x in self._dir: if isinstance(x, Element): content = 1 pad = '\n' + ('\t' * recursive) for x in self._dir: if multiline and content: out += pad if isstr(x): out += quote(x) elif isinstance(x, Element): out += x.__repr__(recursive+1, multiline, inprefixes.copy()) else: raise TypeError, "I wasn't expecting "+`x`+"." if multiline and content: out += '\n' + ('\t' * (recursive-1)) else: if self._dir: out += '...' out += '</'+qname(self._name, inprefixes)+'>' return out def __unicode__(self): text = '' for x in self._dir: text += unicode(x) return ' '.join(text.split()) def __str__(self): return self.__unicode__().encode('utf-8') def __getattr__(self, n): if n[0] == '_': raise AttributeError, "Use foo['"+n+"'] to access the child element." if self._dNS: n = (self._dNS, n) for x in self._dir: if isinstance(x, Element) and x._name == n: return x raise AttributeError, 'No child element named \''+n+"'" def __hasattr__(self, n): for x in self._dir: if isinstance(x, Element) and x._name == n: return True return False def __setattr__(self, n, v): if n[0] == '_': self.__dict__[n] = v else: self[n] = v def __getitem__(self, n): if isinstance(n, type(0)): # d[1] == d._dir[1] return self._dir[n] elif isinstance(n, slice(0).__class__): # numerical slices if isinstance(n.start, type(0)): return self._dir[n.start:n.stop] # d['foo':] == all <foo>s n = n.start if self._dNS and not islst(n): n = (self._dNS, n) out = [] for x in self._dir: if isinstance(x, Element) and x._name == n: out.append(x) return out else: # d['foo'] == first <foo> if self._dNS and not islst(n): n = (self._dNS, n) for x in self._dir: if isinstance(x, Element) and x._name == n: return x raise KeyError def __setitem__(self, n, v): if isinstance(n, type(0)): # d[1] self._dir[n] = v elif isinstance(n, slice(0).__class__): # d['foo':] adds a new foo n = n.start if self._dNS and not islst(n): n = (self._dNS, n) nv = Element(n) self._dir.append(nv) else: # d["foo"] replaces first <foo> and dels rest if self._dNS and not islst(n): n = (self._dNS, n) nv = Element(n); nv._dir.append(v) replaced = False todel = [] for i in range(len(self)): if self[i]._name == n: if replaced: todel.append(i) else: self[i] = nv replaced = True if not replaced: self._dir.append(nv) for i in todel: del self[i] def __delitem__(self, n): if isinstance(n, type(0)): del self._dir[n] elif isinstance(n, slice(0).__class__): # delete all <foo>s n = n.start if self._dNS and not islst(n): n = (self._dNS, n) for i in range(len(self)): if self[i]._name == n: del self[i] else: # delete first foo for i in range(len(self)): if self[i]._name == n: del self[i] break def __call__(self, *_pos, **_set): if _set: for k in _set.keys(): self._attrs[k] = _set[k] if len(_pos) > 1: for i in range(0, len(_pos), 2): self._attrs[_pos[i]] = _pos[i+1] if len(_pos) == 1 is not None: return self._attrs[_pos[0]] if len(_pos) == 0: return self._attrs def __len__(self): return len(self._dir) class Namespace: def __init__(self, uri): self.__uri = uri def __getattr__(self, n): return (self.__uri, n) def __getitem__(self, n): return (self.__uri, n) from xml.sax.handler import EntityResolver, DTDHandler, ContentHandler, ErrorHandler class Seeder(EntityResolver, DTDHandler, ContentHandler, ErrorHandler): def __init__(self): self.stack = [] self.ch = '' self.prefixes = {} ContentHandler.__init__(self) def startPrefixMapping(self, prefix, uri): if not self.prefixes.has_key(prefix): self.prefixes[prefix] = [] self.prefixes[prefix].append(uri) def endPrefixMapping(self, prefix): self.prefixes[prefix].pop() # szf: 5/15/5 if len(self.prefixes[prefix]) == 0: del self.prefixes[prefix] def startElementNS(self, name, qname, attrs): ch = self.ch; self.ch = '' if ch and not ch.isspace(): self.stack[-1]._dir.append(ch) attrs = dict(attrs) newprefixes = {} for k in self.prefixes.keys(): newprefixes[k] = self.prefixes[k][-1] self.stack.append(Element(name, attrs, prefixes=newprefixes.copy())) def characters(self, ch): self.ch += ch def endElementNS(self, name, qname): ch = self.ch; self.ch = '' if ch and not ch.isspace(): self.stack[-1]._dir.append(ch) element = self.stack.pop() if self.stack: self.stack[-1]._dir.append(element) else: self.result = element from xml.sax import make_parser from xml.sax.handler import feature_namespaces def seed(fileobj): seeder = Seeder() parser = make_parser() parser.setFeature(feature_namespaces, 1) parser.setContentHandler(seeder) parser.parse(fileobj) return seeder.result def parse(text): from StringIO import StringIO return seed(StringIO(text)) def load(url): import urllib return seed(urllib.urlopen(url)) def unittest(): parse('<doc>a<baz>f<b>o</b>ob<b>a</b>r</baz>a</doc>').__repr__(1,1) == \ '<doc>\n\ta<baz>\n\t\tf<b>o</b>ob<b>a</b>r\n\t</baz>a\n</doc>' assert str(parse("<doc />")) == "" assert str(parse("<doc>I <b>love</b> you.</doc>")) == "I love you." assert parse("<doc>\nmom\nwow\n</doc>")[0].strip() == "mom\nwow" assert str(parse('<bing> <bang> <bong>center</bong> </bang> </bing>')) == "center" assert str(parse('<doc>\xcf\x80</doc>')) == '\xcf\x80' d = Element('foo', attrs={'foo':'bar'}, children=['hit with a', Element('bar'), Element('bar')]) try: d._doesnotexist raise "ExpectedError", "but found success. Damn." except AttributeError: pass assert d.bar._name == 'bar' try: d.doesnotexist raise "ExpectedError", "but found success. Damn." except AttributeError: pass assert hasattr(d, 'bar') == True assert d('foo') == 'bar' d(silly='yes') assert d('silly') == 'yes' assert d() == d._attrs assert d[0] == 'hit with a' d[0] = 'ice cream' assert d[0] == 'ice cream' del d[0] assert d[0]._name == "bar" assert len(d[:]) == len(d._dir) assert len(d[1:]) == len(d._dir) - 1 assert len(d['bar':]) == 2 d['bar':] = 'baz' assert len(d['bar':]) == 3 assert d['bar']._name == 'bar' d = Element('foo') doc = Namespace("http://example.org/bar") bbc = Namespace("http://example.org/bbc") dc = Namespace("http://purl.org/dc/elements/1.1/") d = parse("""<doc version="2.7182818284590451" xmlns="http://example.org/bar" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:bbc="http://example.org/bbc"> <author>John Polk and John Palfrey</author> <dc:creator>John Polk</dc:creator> <dc:creator>John Palfrey</dc:creator> <bbc:show bbc:station="4">Buffy</bbc:show> </doc>""") assert repr(d) == '<doc version="2.7182818284590451">...</doc>' assert d.__repr__(1) == '<doc xmlns:bbc="http://example.org/bbc" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns="http://example.org/bar" version="2.7182818284590451"><author>John Polk and John Palfrey</author><dc:creator>John Polk</dc:creator><dc:creator>John Palfrey</dc:creator><bbc:show bbc:station="4">Buffy</bbc:show></doc>' assert d.__repr__(1,1) == '<doc xmlns:bbc="http://example.org/bbc" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns="http://example.org/bar" version="2.7182818284590451">\n\t<author>John Polk and John Palfrey</author>\n\t<dc:creator>John Polk</dc:creator>\n\t<dc:creator>John Palfrey</dc:creator>\n\t<bbc:show bbc:station="4">Buffy</bbc:show>\n</doc>' assert repr(parse("<doc xml:lang='en' />")) == '<doc xml:lang="en"></doc>' assert str(d.author) == str(d['author']) == "John Polk and John Palfrey" assert d.author._name == doc.author assert str(d[dc.creator]) == "John Polk" assert d[dc.creator]._name == dc.creator assert str(d[dc.creator:][1]) == "John Palfrey" d[dc.creator] = "Me!!!" assert str(d[dc.creator]) == "Me!!!" assert len(d[dc.creator:]) == 1 d[dc.creator:] = "You!!!" assert len(d[dc.creator:]) == 2 assert d[bbc.show](bbc.station) == "4" d[bbc.show](bbc.station, "5") assert d[bbc.show](bbc.station) == "5" e = Element('e') e.c = '<img src="foo">' assert e.__repr__(1) == '<e><c>&lt;img src="foo"></c></e>' e.c = '2 > 4' assert e.__repr__(1) == '<e><c>2 > 4</c></e>' e.c = 'CDATA sections are <em>closed</em> with ]]>.' assert e.__repr__(1) == '<e><c>CDATA sections are &lt;em>closed&lt;/em> with ]]&gt;.</c></e>' e.c = parse('<div xmlns="http://www.w3.org/1999/xhtml">i<br /><span></span>love<br />you</div>') assert e.__repr__(1) == '<e><c><div xmlns="http://www.w3.org/1999/xhtml">i<br /><span></span>love<br />you</div></c></e>' e = Element('e') e('c', 'that "sucks"') assert e.__repr__(1) == '<e c="that &quot;sucks&quot;"></e>' assert quote("]]>") == "]]&gt;" assert quote('< dkdkdsd dkd sksdksdfsd fsdfdsf]]> kfdfkg >') == '&lt; dkdkdsd dkd sksdksdfsd fsdfdsf]]&gt; kfdfkg >' assert parse('<x a="&lt;"></x>').__repr__(1) == '<x a="&lt;"></x>' assert parse('<a xmlns="http://a"><b xmlns="http://b"/></a>').__repr__(1) == '<a xmlns="http://a"><b xmlns="http://b"></b></a>' if __name__ == '__main__': unittest()
Python
from _beatbox import _tPartnerNS, _tSObjectNS, _tSoapNS, SoapFaultError, SessionTimeoutError from _beatbox import Client as XMLClient #from _beatbox import MetaClient from python_client import Client as PythonClient from python_client import MetaClient as PythonMetaClient __all__ = ('XMLClient', '_tPartnerNS', '_tSObjectNS', '_tSoapNS', 'tests', 'SoapFaultError', 'SessionTimeoutError', 'PythonClient', 'PythonMetaClient','MetaClient')
Python
# acct_lookup.py import os import beatbox from google.appengine.ext.webapp import template from google.appengine.ext.webapp import RequestHandler class AcctLookupHandler(RequestHandler): def get(self): path = os.path.join(os.path.dirname(__file__), 'templates/acct_lookup.html') self.response.out.write(template.render(path, {'accounts': []})) def post(self): # Retrieve username, password and account from post data username = self.request.get('uid') password = self.request.get('pwd') accountName = self.request.get('account') # Attempt a login self.sforce = beatbox.PythonClient() try: login_result = self.sforce.login(username, password) except beatbox.SoapFaultError, errorInfo: path = os.path.join(os.path.dirname(__file__), 'templates/simple_login_failed.html') self.response.out.write(template.render(path, {'errorCode': errorInfo.faultCode, 'errorString': errorInfo.faultString})) return # Query for accounts query_result = self.sforce.query("SELECT Id, Name, Phone, WebSite FROM Account WHERE Name LIKE '%" + accountName + "%'") records = query_result['records'] # Render the output template_values = {'accounts': records, 'username': username, 'password': password, 'accountName': accountName}; path = os.path.join(os.path.dirname(__file__), 'templates/acct_lookup.html') self.response.out.write(template.render(path, template_values))
Python
# create_contact.py import os import beatbox from google.appengine.ext.webapp import template from google.appengine.ext.webapp import RequestHandler class CreateContactHandler(RequestHandler): def get(self): self.redirect('/static/create_contact_input.html') def post(self): # Retrieve username, password and account from post data username = self.request.get('uid') password = self.request.get('pwd') firstName = self.request.get('firstName') lastName = self.request.get('lastName') phone = self.request.get('phone') email = self.request.get('email') # Attempt a login self.sforce = beatbox.PythonClient() try: login_result = self.sforce.login(username, password) except beatbox.SoapFaultError, errorInfo: path = os.path.join(os.path.dirname(__file__), 'templates/simple_login_failed.html') self.response.out.write(template.render(path, {'errorCode': errorInfo.faultCode, 'errorString': errorInfo.faultString})) return # Create the new contact newContact = {'FirstName': firstName, 'LastName': lastName, 'Phone': phone, 'Email': email, 'LeadSource': 'Google AppEngine', 'type': 'Contact'} create_result = self.sforce.create([newContact]) # Render the output template_values = {'success': create_result[0]['success'], 'objId': create_result[0]['id'], 'errors': create_result[0]['errors']} path = os.path.join(os.path.dirname(__file__), 'templates/create_contact_result.html') self.response.out.write(template.render(path, template_values))
Python
# unit_test.py import os import beatbox from datetime import datetime import logging from google.appengine.api import memcache from google.appengine.ext.webapp import template from google.appengine.ext.webapp import RequestHandler class UnitTestHandler(RequestHandler): def get(self): op = self.request.get('op') sid = self.request.get('sid') logging.info( sid) if (sid == '' or sid == None): self.redirect('/static/unit_test_login.html') return if ( op == '' ): logging.info(memcache.get('userInfo')) unifo = memcache.get('userInfo') template_values = {'user_id': unifo.get('userId'), 'server_url': memcache.get("serverUrl") , 'session_id': sid}; path = os.path.join(os.path.dirname(__file__), 'templates/unit_test.html') self.response.out.write(template.render(path, template_values)) return client = Client() if (op == 'query'): soql = 'select name from Account limit 12' self.response.out.write('<b>'+soql+'</b>') query_result = client.query( soql ) for account in query_result['records'] : self.response.out.write('<li>' + account['Name'] ) if (op == 'login'): login_result = client.login( memcache.get('username'), memcache.get('password') ) self.response.out.write( login_result ) if (op == 'create'): sobjects = [] new_acc = { 'type': 'Account', 'name' : 'new GAE account' } sobjects.append(new_acc) results = client.create(sobjects) self.response.out.write( results ) if (op == 'delete'): query_result = client.query( "select id from Account where name like 'new GAE account%' limit 1") accounts = [] for account in query_result['records'] : accounts.append( account['Id'] ) if ( accounts.__len__() < 1 ): self.response.out.write('no account found with name : new GAE account ') else : results = client.delete( accounts ) self.response.out.write( results ) if ( op == 'update'): query_result = client.query( "select id from Account where name like 'new GAE account%' limit 1") if ( query_result['records'].__len__() < 1 ): self.response.out.write('no account found with name : new GAE account ') else : account = query_result['records'][0] self.response.out.write( account ) account['Name'] = 'new GAE account UPDATED' results = client.update( account ) self.response.out.write( results ) if (op == 'global' ): describe = client.describeGlobal() self.response.out.write( describe ) if (op == 'describeAcc'): # describeSObjects returns a list of dictionaries dict = client.describeSObjects('Account')[0] self.response.out.write( '<dl>') for key in dict.keys(): self.response.out.write( '<dt>'+ key + '</dt><dd>' + str(dict[key]) + '</dd>' ) if ( op == 'retrieve' ): query_result = client.query( "select id from Account where name like 'new GAE account%' limit 1") if ( query_result['records'].__len__() < 1 ): self.response.out.write('no account found with name : new GAE account ') else: accounts = [] for account in query_result['records'] : accounts.append( account['Id'] ) results = client.retrieve( 'Name,Id','Account', accounts ) self.response.out.write( results ) if ( op == 'getDeleted' ): now = datetime.now() then = datetime(now.year, now.month, now.day-1 ) results = client.getDeleted('Account', then, now ) self.response.out.write( results ) if ( op == 'getUpdated' ): now = datetime.now() then = datetime(now.year, now.month, now.day-1 ) results = client.getUpdated('Account', then, now ) self.response.out.write( results ) if ( op == 'getUserInfo' ): results = client.getUserInfo( ) self.response.out.write( results ) if (op == 'describeTabs' ): pass # add a back link self.response.out.write('<p /><b><a href="/unittest?sid='+memcache.get("sessionId")+'">back</a></b>' ) def post(self): # Retrieve username and password from post data login_result = verifyLogin(self) if ( login_result == None ): # render a failed login path = os.path.join(os.path.dirname(__file__), 'templates/test_login_failed.html') self.response.out.write(template.render(path, {'errorCode': memcache.get('errorCode'), 'errorString': memcache.get('errorString') })) return # login was ok template_values = {'user_id': login_result['userId'], 'server_url': login_result['serverUrl'], 'session_id': login_result['sessionId']}; # Render the output path = os.path.join(os.path.dirname(__file__), 'templates/unit_test.html') self.response.out.write(template.render(path, template_values)) def Client(): bbox = beatbox.PythonClient() bbox.useSession(memcache.get('sessionId'), memcache.get('serverUrl')) return bbox def verifyLogin(self): """ Insure that we have a session id or have a login username and can use it store our session info in memcache """ username = self.request.get('uid') password = self.request.get('pwd') memcache.set_multi({ 'username':username, 'password':password}) self.sforce = beatbox.PythonClient() login_result = None try: login_result = self.sforce.login(username, password) except beatbox.SoapFaultError, errorInfo: memcache.set_multi( {'errorCode': errorInfo.faultCode, 'errorString': errorInfo.faultString}) else: # caution: this method of storing session id is not viable for multiple users # of this application since all users will have access to the same session id and concurrent # users will overwrite this info. this method will work for a single user at a time memcache.set_multi({ 'sessionId': login_result['sessionId'], 'serverUrl': login_result['serverUrl'], 'metadataServerUrl' : login_result['metadataServerUrl'], 'userInfo': login_result['userInfo']} , time=36000) logging.info( memcache.get("sessionId") ) logging.info( memcache.get("serverUrl") ) logging.info( memcache.get("metadataServerUrl") ) logging.info( memcache.get("userInfo") ) return login_result
Python
# simple_login.py import os import beatbox from google.appengine.ext.webapp import template from google.appengine.ext.webapp import RequestHandler class SimpleLoginHandler(RequestHandler): def post(self): # Retrieve username and password from post data username = self.request.get('uid') password = self.request.get('pwd') # Attempt a login self.sforce = beatbox.PythonClient() try: login_result = self.sforce.login(username, password) except beatbox.SoapFaultError, errorInfo: path = os.path.join(os.path.dirname(__file__), 'templates/simple_login_failed.html') self.response.out.write(template.render(path, {'errorCode': errorInfo.faultCode, 'errorString': errorInfo.faultString})) else: # Grab the resulting session id template_values = {'user_id': login_result['userId'], 'server_url': login_result['serverUrl'], 'session_id': login_result['sessionId']}; # Render the output path = os.path.join(os.path.dirname(__file__), 'templates/simple_login_result.html') self.response.out.write(template.render(path, template_values))
Python
#!/usr/bin/env python from django.core.management import execute_manager import imp try: imp.find_module('settings') # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__) sys.exit(1) import settings if __name__ == "__main__": execute_manager(settings)
Python
#!/usr/bin/env python from django.core.management import execute_manager import imp try: imp.find_module('settings') # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__) sys.exit(1) import settings if __name__ == "__main__": execute_manager(settings)
Python
from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'mysite.views.home', name='home'), # url(r'^mysite/', include('mysite.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), )
Python
# Django settings for mysite project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # URL prefix for admin static files -- CSS, JavaScript and images. # Make sure to use a trailing slash. # Examples: "http://foo.com/static/admin/", "/static/admin/". ADMIN_MEDIA_PREFIX = '/static/admin/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = '*hs872)$^f!$bg819lvh5wmav-*y4il34iyjnx67^)9^yx6%xe' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'mysite.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: # 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } }
Python
import cgi import datetime import urllib import wsgiref.handlers from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class Greeting(db.Model): """Models an individual Guestbook entry with an author, content, and date.""" author = db.UserProperty() content = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) def guestbook_key(guestbook_name=None): """Constructs a datastore key for a Guestbook entity with guestbook_name.""" return db.Key.from_path('Guestbook', guestbook_name or 'default_guestbook') class MainPage(webapp.RequestHandler): def get(self): self.response.out.write('<html><body>') guestbook_name=self.request.get('guestbook_name') # Ancestor Queries, as shown here, are strongly consistent with the High # Replication datastore. Queries that span entity groups are eventually # consistent. If we omitted the ancestor from this query there would be a # slight chance that Greeting that had just been written would not show up # in a query. greetings = db.GqlQuery("SELECT * " "FROM Greeting " "WHERE ANCESTOR IS :1 " "ORDER BY date DESC LIMIT 10", guestbook_key(guestbook_name)) for greeting in greetings: if greeting.author: self.response.out.write( '<b>%s</b> wrote:' % greeting.author.nickname()) else: self.response.out.write('An anonymous person wrote:') self.response.out.write('<blockquote>%s</blockquote>' % cgi.escape(greeting.content)) self.response.out.write(""" <form action="/sign?%s" method="post"> <div><textarea name="content" rows="3" cols="60"></textarea></div> <div><input type="submit" value="Sign Guestbook"></div> </form> <hr> <form>Guestbook name: <input value="%s" name="guestbook_name"> <input type="submit" value="switch"></form> </body> </html>""" % (urllib.urlencode({'guestbook_name': guestbook_name}), cgi.escape(guestbook_name))) class Guestbook(webapp.RequestHandler): def post(self): # We set the same parent key on the 'Greeting' to ensure each greeting is in # the same entity group. Queries across the single entity group will be # consistent. However, the write rate to a single entity group should # be limited to ~1/second. guestbook_name = self.request.get('guestbook_name') greeting = Greeting(parent=guestbook_key(guestbook_name)) if users.get_current_user(): greeting.author = users.get_current_user() greeting.content = self.request.get('content') greeting.put() self.redirect('/?' + urllib.urlencode({'guestbook_name': guestbook_name})) application = webapp.WSGIApplication([ ('/', MainPage), ('/sign', Guestbook) ], debug=True) def main(): run_wsgi_app(application) if __name__ == '__main__': main()
Python
from django.db import models # Create your models here.
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('misc.views', (r'^about/', 'about'), )
Python
from django.http import Http404, HttpResponseRedirect, HttpResponse from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.auth import logout, login, authenticate from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.contrib.auth.views import password_change, password_change_done from django.db import models from profile.models import ProfileImage, UserProfile from profile.forms import UploadProfilePhotoForm, EditProfileInfoForm from datetime import datetime from common import globalvars import urllib, re, settings def about(request): variables = RequestContext(request, { }) return render_to_response('misc/about.html', variables)
Python
#!/usr/bin/env python from django.core.management import execute_manager import sys try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
from django.db import models # Create your models here.
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('accounts.views', # Example: # (r'^dishpop/', include('dishpop.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^user/(?P<user_name>\w+)/account/$', 'account'), (r'^user/(?P<user_name>\w+)/account/password_change$', 'change_password'), )
Python
from django.http import Http404, HttpResponseRedirect, HttpResponse from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.auth import logout, login, authenticate from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import PasswordChangeForm from datetime import datetime def GetUser(user_name): try: return User.objects.get(username=user_name) except User.DoesNotExist: raise Http404('Requested user not found.') @login_required def account(request, user_name): user = GetUser(user_name) variables = RequestContext(request, { 'user_public' : user, }) return render_to_response('registration/account.html', variables) def change_password(request, user_name): if request.method == 'POST': form = PasswordChangeForm(user=request.user, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/user/'+ user_name + '/') else: form = PasswordChangeForm(user=request.user) variables = RequestContext(request, { 'form': form }) return render_to_response('registration/password_change.html', variables)
Python
from django import forms from django.forms import ModelForm from reviews.models import DishImage import re from django.contrib.auth.models import User RATING_CHOICES = ( ('1', '1 Horrible'), ('2', '2 Poor'), ('3', '3 Just ok'), ('4', '4 Good'), ('5', '5 Excellent'), ) class SearchForm(forms.Form): query = forms.CharField(initial='What kind of food?', max_length=50) location = forms.CharField(initial='Where to look?', max_length=50) class UploadDishPhotoForm(ModelForm): class Meta: model = DishImage exclude = ('dish', 'user',) class EditTagsForm(forms.Form): dish_id = forms.IntegerField(widget=forms.HiddenInput, required=True) tags = forms.CharField(max_length=100, required=False) # this is currently used for adding new dish AND adding a review... class ReviewForm(forms.Form): name = forms.CharField() place = forms.CharField() tags = forms.CharField(required=False) text = forms.CharField(widget=forms.Textarea, required=False) rating = forms.ChoiceField(choices=RATING_CHOICES) review_id = forms.IntegerField(widget=forms.HiddenInput, required=False) class RegistrationForm(forms.Form): username = forms.CharField(label=u'Username', max_length=30) email = forms.EmailField(label=u'Email') password1 = forms.CharField( label=u'Password', widget=forms.PasswordInput() ) password2 = forms.CharField( label=u'Password (Again)', widget=forms.PasswordInput() ) def clean_password2(self): if 'password1' in self.cleaned_data: password1 = self.cleaned_data['password1'] password2 = self.cleaned_data['password2'] if password1 == password2: return password2 raise forms.ValidationError('Passwords do not match.') def clean_username(self): username = self.cleaned_data['username'] if not re.search(r'^\w+$', username): raise forms.ValdiationError('Username can only contain ' 'alphanumeric characters and the underscore.') try: User.objects.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError('Username is already taken.')
Python
from imagekit.specs import ImageSpec from imagekit import processors # first we define our thumbnail resize processor class ResizeThumb(processors.Resize): width = 100 height = 75 crop = True class ResizeMedium(processors.Resize): width = 275 height = 275 crop = True # now we define a display size resize processor class ResizeDisplay(processors.Resize): width = 600 class EnhanceMedium(processors.Adjustment): contrast = 1.2 sharpness = 1.1 # now lets create an adjustment processor to enhance the image at small sizes class EnchanceThumb(processors.Adjustment): contrast = 1.2 sharpness = 1.1 class MediumDisplay(ImageSpec): pre_cache = True processors = [ResizeMedium, EnhanceMedium] # now we can define our thumbnail spec class Thumbnail(ImageSpec): #access_as = 'thumbnail_image' pre_cache = True processors = [ResizeThumb, EnchanceThumb] # and our display spec class Display(ImageSpec): increment_count = True processors = [ResizeDisplay]
Python
from django.db import models from tagging.models import Tag from common.models import NameSlugModel, DateAwareModel, MyImageModel, UserOwnedModel from django.contrib.gis.db import models class Place(NameSlugModel, DateAwareModel): geometry = models.PointField(srid=4326) objects = models.GeoManager() def __unicode__(self): return self.name class Dish(NameSlugModel, DateAwareModel): place = models.ForeignKey(Place) # Dish can be a specific food or a combination of foods # where each food has its own tag. tags = models.ManyToManyField(Tag, null=True, blank=True) geometry = models.PointField(srid=4326, blank=True, editable=False) objects = models.GeoManager() # Always set geometry equal to geometry of corresponding place. # This is to get around not being able to "order by" distance if model # does not contain a PointField. def save(self, *args, **kwargs): self.geometry = self.place.geometry super(Dish, self).save(*args, **kwargs) def order_by_distance(dish_list, pnt): place_list = [d.place for d in dish_list] def __unicode__(self): return self.name class PlaceImage(MyImageModel, UserOwnedModel): place = models.ForeignKey(Place) class DishImage(MyImageModel, UserOwnedModel): dish = models.ForeignKey(Dish) class Review(DateAwareModel, UserOwnedModel): text = models.TextField(blank=True) dish = models.ForeignKey(Dish) rating = models.IntegerField(blank=True, null=True) tags = models.ManyToManyField(Tag, null=True, blank=True) def __unicode__(self): return str(self.created_date) + ' ' + str(self.dish) + ' by ' + str(self.user)
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('reviews.views', # Example: # (r'^dishpop/', include('dishpop.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^$', 'home'), (r'^tag/(?P<tag_id>\d+)/$', 'tag'), #(r'^user/(?P<user_name>\w+)/$', 'user_page'), (r'^dish/(?P<dish_id>\d+)/$', 'dish'), (r'^place/(?P<place_slug>[a-z0-9-]+)/$', 'place'), (r'^submit/dish/$', 'submit_dish'), (r'^submit/photo/dish/(?P<dish_id>\d+)/$', 'add_photo'), (r'^submit/tags/dish/(?P<dish_id>\d+)/$', 'submit_tags'), (r'^submit/review/dish/(?P<dish_id>\d+)/$', 'submit_review'), (r'^submit/review/dish/$', 'submit_dish'), (r'^delete/$', 'delete_review_or_image'), (r'^search/$', 'search'), (r'^logout/$', 'log_user_out'), )
Python
from django.contrib import admin from reviews.models import Place, Dish, PlaceImage, DishImage, Review from tagging.models import Tag, Tag_Relation class ImageAdmin(admin.ModelAdmin): list_display = ('name', 'admin_thumbnail_view',) class PlaceAdmin(admin.ModelAdmin): exclude = ('modified_date', 'created_date') class DishAdmin(admin.ModelAdmin): exclude = ('modified_date', 'created_date') admin.site.register(Place) admin.site.register(Dish) admin.site.register(PlaceImage, ImageAdmin) admin.site.register(DishImage, ImageAdmin) admin.site.register(Review) admin.site.register(Tag) admin.site.register(Tag_Relation)
Python
from django.http import Http404, HttpResponseRedirect, HttpResponse from django.template import RequestContext from django.contrib.auth import logout, login, authenticate from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import PasswordChangeForm from django.contrib.gis.geos import fromstr from django.contrib.gis.measure import D # D is a short for Distance from django.shortcuts import render_to_response, get_object_or_404 from datetime import datetime from reviews.models import Dish, Place, Review, DishImage from reviews.forms import ReviewForm, RegistrationForm, UploadDishPhotoForm, SearchForm, EditTagsForm from tagging.models import Tag from tagging.utils import parse_tags, edit_string_for_tags def add_search_form_processor(request): form = SearchForm() return {'search_form': form } def register_page(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = User.objects.create_user( username = cd['username'].lower(), password = cd['password1'], email = cd['email'] ) # automagically log user in user = authenticate(username = cd['username'].lower(), password = cd['password1']) login(request, user) return HttpResponseRedirect('/') else: form = RegistrationForm() variables = RequestContext(request, { 'form': form }) return render_to_response('registration/register.html', variables) def log_user_out(request): logout(request) return HttpResponseRedirect('/') def user_page(request, user_name): try: user = User.objects.get(username=user_name) except User.DoesNotExist: raise Http404('Requested user not found.') print user.username variables = RequestContext(request, { 'user_public' : user, 'show_edit' : user_name == request.user.username, }) return render_to_response('reviews/user_page.html', variables) def home(request): '''List all dishes and their corresponding tags.''' form = SearchForm() num_latest = 10 dishes = Dish.objects.all().order_by('-created_date')[:num_latest] variables = RequestContext(request, { 'form': form, 'dishes': dishes, 'show_results': False, 'show_tags': True, 'show_user': True, 'show_edit' : request.user.is_authenticated(), 'num_latest': num_latest, }) return render_to_response('reviews/main_page.html', variables) def search(request): form = SearchForm() dishes = Dish.objects.all() if 'query' in request.GET: query = request.GET['query'].strip() if query: form = SearchForm({'query' : query}) dishes = dishes.filter(name__icontains=query) if 'lat' in request.GET and 'lng' in request.GET: # filter dishes based on lat, lng lat = request.GET['lat'].strip() lng = request.GET['lng'].strip() if lat and lng: # need to populate form with search value like above pnt = fromstr('POINT(' + lat + ' ' + lng + ')', srid=4326) dishes = dishes.filter(geometry__distance_lte=(pnt, D(mi=10))) if 'sort_by' in request.GET: # sort by some criteria criteria = request.GET['sort_by'].strip() if criteria == "distance": dishes = dishes.distance(pnt).order_by('distance') # assumes pnt is already created variables = RequestContext(request, { 'form': form, 'dishes': dishes, 'show_tags': True, 'show_user': True, 'show_edit' : request.user.is_authenticated(), }) if request.GET.has_key('ajax'): return render_to_response('reviews/dish_list.html', variables) else: return render_to_response('reviews/main_page.html', variables) def tag(request, tag_id): '''List all the dishes associated with the specified tag.''' tag = get_object_or_404(Tag, id=tag_id) related_tags = tag.all_related_tags() return render_to_response('reviews/tag.html', RequestContext(request, {'tag' : tag, 'related_tags' : related_tags})) def place(request, place_slug): place = get_object_or_404(Place, slug=place_slug) variables = RequestContext(request, { 'place' : place, 'show_edit' : request.user.is_authenticated() }) return render_to_response('reviews/place.html', variables) def dish(request, dish_id): '''List all the reviews for the given dish''' d = get_object_or_404(Dish, id=dish_id) reviews = d.review_set.all() avg_rating = None if reviews: avg_rating = float(sum([rev.rating for rev in reviews]))/len(reviews) variables = RequestContext(request, { 'dish' : d, 'avg_rating' : avg_rating }) return render_to_response('reviews/dish.html', variables) @login_required def add_photo(request, dish_id): if dish_id: dish = get_object_or_404(Dish, id=dish_id) if request.method == 'POST': form = UploadDishPhotoForm(request.POST, request.FILES) if form.is_valid(): new_dish_image = form.save(commit=False) new_dish_image.dish = dish new_dish_image.user = request.user new_dish_image.save() return HttpResponseRedirect('/dish/' + str(dish.id)) else: form = UploadDishPhotoForm() return render_to_response('reviews/upload.html', {'form': form}, context_instance=RequestContext(request)) @login_required def submit_dish(request): dish_id = None if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): cd = form.cleaned_data placename = cd['place'] place, dummy = Place.objects.get_or_create(name = placename) dish, dummy = Dish.objects.get_or_create(name = cd['name'], place = place) dish_id = dish.id return submit_review(request, dish_id) else: initial_data = {'text': 'Write stuff here.'} form = ReviewForm(initial = initial_data) return render_to_response('reviews/submit_form_page.html', {'form': form}, context_instance=RequestContext(request)) @login_required def submit_tags(request, dish_id): dish = get_object_or_404(Dish, id=dish_id) ajax = 'ajax' in request.GET initial_data = {} if request.method == 'POST': form = EditTagsForm(request.POST) if form.is_valid(): cd = form.cleaned_data # parse tags and add to dish # what if users are stupid and tag dishes badly? tag_string = cd['tags'] tag_list = parse_tags(tag_string) #tag_obj_list = [] dish.tags.clear() for tag in tag_list: tag_obj, dummy = Tag.objects.get_or_create(name = tag) #tag_obj_list.append(tag_obj) if not tag_obj in dish.tags.all(): dish.tags.add(tag_obj) if ajax: variables = RequestContext(request, { 'dish': dish, 'show_edit': request.user.is_authenticated(), }) return render_to_response( 'reviews/tag_list.html', variables ) return HttpResponseRedirect('/dish/' + str(dish.id)) else: if ajax: return HttpResponse(u'failure') tags_string = edit_string_for_tags(dish.tags.all()) initial_data['tags'] = tags_string initial_data['dish_id'] = dish_id form = EditTagsForm( initial = initial_data ) if ajax: return render_to_response('reviews/edit_tags_form.html', {'form': form}, context_instance=RequestContext(request)) return render_to_response('reviews/submit_form_page.html', {'form': form}, context_instance=RequestContext(request)) @login_required def delete_review_or_image(request): if 'review_id' in request.GET: review_id = request.GET['review_id'] review = get_object_or_404(Review, id=review_id) review.delete() elif 'photo_id' in request.GET: photo_id = request.GET['photo_id'] photo = get_object_or_404(DishImage, id=photo_id) photo.delete() return HttpResponseRedirect('/user/' + str(request.user.username)) @login_required def submit_review(request, dish_id): dish = get_object_or_404(Dish, id=dish_id) initial_data = {} if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): cd = form.cleaned_data if 'review_id' in cd and cd['review_id']: review_id = cd['review_id'] review = Review.objects.get(id = review_id) review.text = cd['text'] review.rating = cd['rating'] else: review = Review.objects.create(text = cd['text'], dish = dish, user = request.user, rating = cd['rating']) # parse tags and add to dish # what if users are stupid and tag dishes badly? tag_string = cd['tags'] tag_list = parse_tags(tag_string) for tag in tag_list: tag_obj, dummy = Tag.objects.get_or_create(name = tag) tag_obj.review_set.add(review) if not tag_obj in dish.tags.all(): dish.tags.add(tag_obj) dish.review_set.add(review) return HttpResponseRedirect('/dish/' + str(dish.id)) elif 'review_id' in request.GET: # case for editing an existing review review_id = request.GET['review_id'] try: review = Review.objects.get(id = review_id) tags_string = edit_string_for_tags(review.tags.all()) initial_data['tags'] = tags_string initial_data['text'] = review.text initial_data['rating'] = review.rating initial_data['review_id'] = review.id except (Review.DoesNotExist): pass else: # case for new review initial_data['text'] = 'Write stuff here.' initial_data['name'] = dish.name initial_data['place'] = dish.place form = ReviewForm( initial = initial_data ) return render_to_response('reviews/submit_form_page.html', {'form': form}, context_instance=RequestContext(request)) # def add_dish(request): # #dish = get_object_or_404(Dish, id=dish_id) # if request.method == 'POST': # form = NewDishForm(request.POST) # if form.is_valid(): # cd = form.cleaned_data # dish = Dish.objects.create(name = cd['name'], # place = cd['place']) # review.save() # return HttpResponseRedirect('/') # else: # form = ReviewForm( # initial = {'text': 'Write stuff here.'} # ) # return render_to_response('reviews/review.html', {'form': form, 'dish': dish}, # context_instance=RequestContext(request)) # def add_review(request, dish_id): # dish = get_object_or_404(Dish, id=dish_id) # try: # review = Review.objects.create(text=str(request.POST['review_text']), dish=dish) # except (KeyError): # # Redisplay the review form. # return render_to_response('reviews/review.html', { # 'dish': dish, # 'error_message': "You didn't seleAdasdfasfct a choice.", # }, context_instance=RequestContext(request)) # else: # review.save() # # Always return an HttpResponseRedirect after successfully dealing # # with POST data. This prevents data from being posted twice if a # # user hits the Back button. # return HttpResponseRedirect(reverse('reviews.views.dish', args=(dish.id,)))
Python
#!/usr/bin/env python from django.core.management import execute_manager import sys try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
from django.conf.urls.defaults import * import os # Uncomment the next two lines to enable the admin:## from django.contrib import admin admin.autodiscover() site_media = os.path.join(os.path.dirname(__file__), 'site_media') urlpatterns = patterns('', # Example: # (r'^kokoomi/', include('kokoomi.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^', include('reviews.urls')), (r'^', include('profile.urls')), (r'^', include('accounts.urls')), (r'^', include('misc.urls')), (r'^admin/', include(admin.site.urls)), (r'^login/$', 'django.contrib.auth.views.login'), (r'^register/$', 'reviews.views.register_page'), # consider moving this out (r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': site_media}), )
Python
from django import forms from django.forms import ModelForm from django.contrib.auth.models import User from profile.models import ProfileImage, UserProfile class UploadProfilePhotoForm(ModelForm): class Meta: model = ProfileImage exclude = ('user', 'isPrimary', 'name') class EditProfileInfoForm(ModelForm): class Meta: model = UserProfile exclude = ('user')
Python
from imagekit.specs import ImageSpec from imagekit import processors # first we define our thumbnail resize processor class ResizeThumb(processors.Resize): width = 100 height = 75 crop = True # now we define a display size resize processor class ResizeDisplay(processors.Resize): width = 250 # now lets create an adjustment processor to enhance the image at small sizes class EnchanceThumb(processors.Adjustment): contrast = 1.2 sharpness = 1.1 # now we can define our thumbnail spec class Thumbnail(ImageSpec): #access_as = 'thumbnail_image' pre_cache = True processors = [ResizeThumb, EnchanceThumb] # and our display spec class Display(ImageSpec): increment_count = True processors = [ResizeDisplay]
Python
from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from common.models import MyImageModel, UserOwnedModel class ProfileImage(MyImageModel, UserOwnedModel): isPrimary = models.BooleanField() class IKOptions: # This inner class is where we define the ImageKit options for the model spec_module = 'kokoomi.profile.specs' cache_dir = 'images' image_field = 'image' save_count_as = 'num_views' class UserProfile(models.Model): user = models.OneToOneField(User) location = models.CharField(max_length=255,blank=True) website = models.URLField(blank=True) def create_profile(sender, **kw): user = kw["instance"] if kw["created"]: profile = UserProfile(user=user) profile.save() post_save.connect(create_profile, sender=User, dispatch_uid="users-profilecreation-signal")
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('profile.views', # Example: # (r'^dishpop/', include('dishpop.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^user/(?P<user_name>\w+)/$', 'profile'), (r'^user/(?P<user_name>\w+)/profilepic$', 'upload_photo'), (r'^user/(?P<user_name>\w+)/edit$', 'edit_profile'), (r'^user/(?P<user_name>\w+)/profilepic/(?P<profileimg_id>\d+)/c$', 'change_photo'), (r'^user/(?P<user_name>\w+)/profilepic/(?P<profileimg_id>\d+)/d$', 'delete_photo'), )
Python
from django.http import Http404, HttpResponseRedirect, HttpResponse from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.auth import logout, login, authenticate from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.contrib.auth.views import password_change, password_change_done from django.db import models from profile.models import ProfileImage, UserProfile from profile.forms import UploadProfilePhotoForm, EditProfileInfoForm from datetime import datetime from common import globalvars import urllib, re, settings def GetUser(user_name): try: return User.objects.get(username=user_name) except User.DoesNotExist: raise Http404('Requested user not found.') def GetDefaultImageUrl(user): if user.profileimage_set.count() > 0: media_url = user.profileimage_set.order_by('modified_date').reverse()[0].mediumdisplay.url else: media_url = globalvars.GetGenericAvatarImgURL() return media_url @login_required def profile(request, user_name): user = GetUser(user_name) review_dict = [] # match the dish with the dishimage dish_imgs = user.dishimage_set.all() reviews = user.review_set.all() for review in reviews: try: img_url = dish_imgs.filter(dish=review.dish)[0].thumbnail.url review_dict.append((review, img_url)) except: review_dict.append((review, globalvars.GetGenericFoodImgURL())) variables = RequestContext(request, { 'user_public' : user, 'profile' : user.get_profile(), 'media_url' : GetDefaultImageUrl(user), 'review_dict' : review_dict, }) return render_to_response('profile/profile.html', variables) @login_required def edit_profile(request, user_name): if request.method == 'POST': form = EditProfileInfoForm(request.POST) if form.is_valid(): userprofile = UserProfile.objects.get(user=request.user) if form.cleaned_data['location'] != "": userprofile.location = form.cleaned_data['location'] if form.cleaned_data['website'] != "": userprofile.website = form.cleaned_data['website'] userprofile.save() return HttpResponseRedirect('/user/' + user_name) else: form = EditProfileInfoForm() user = GetUser(user_name) variables = RequestContext(request, { 'user_public' : user, 'media_url' : GetDefaultImageUrl(user), }) return render_to_response('profile/profile_edit.html', {'form': form}, context_instance=variables) @login_required def upload_photo(request, user_name): if request.method == 'POST': form = UploadProfilePhotoForm(request.POST, request.FILES) if form.is_valid(): new_profile_image = form.save(commit=False) new_profile_image.name = user_name new_profile_image.isPrimary = True new_profile_image.user = request.user new_profile_image.save() return HttpResponseRedirect('/user/' + user_name) else: form = UploadProfilePhotoForm() variables = RequestContext(request, { 'media_url' : GetDefaultImageUrl(GetUser(user_name)), }) return render_to_response('profile/profilepic.html', {'form': form}, context_instance=variables) @login_required def change_photo(request, user_name, profileimg_id): try: user = User.objects.get(username=user_name) except User.DoesNotExist: raise Http404('Requested user not found.') img = user.profileimage_set.get(pk=profileimg_id) img.modified_date = datetime.now() img.save() variables = RequestContext(request, { 'user_public' : user, 'media_url' : GetDefaultImageUrl(user), }) return HttpResponseRedirect('/user/' + user_name) @login_required def delete_photo(request, user_name, profileimg_id): try: user = User.objects.get(username=user_name) except User.DoesNotExist: raise Http404('Requested user not found.') user.profileimage_set.get(pk=profileimg_id).delete() variables = RequestContext(request, { 'user_public' : user, 'media_url' : GetDefaultImageUrl(user), }) return HttpResponseRedirect('/user/' + user_name + '/profilepic')
Python
# Django settings for kokoomi project. import os SITE_ROOT = os.path.abspath(os.path.dirname(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'kokoomi_db', # Or path to database file if using sqlite3. 'USER': 'django', # Not used with sqlite3. 'PASSWORD': 'password', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = os.path.join(SITE_ROOT, 'site_media') # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '/site_media/' LOGIN_URL = '/login/' LOGIN_REDIRECT_URL = '/' # consider making this the user's profile or account page AUTH_PROFILE_MODULE = 'profile.UserProfile' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY = '@&$gmbry6m+%^^f5(8hs2k@64i3lsxahec^%_6@z5&7z29%ywj' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'kokoomi.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(SITE_ROOT, 'templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', 'django.contrib.gis', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'reviews', 'tagging', 'imagekit', 'common', 'profile', 'accounts', 'misc', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.contrib.messages.context_processors.messages', 'reviews.views.add_search_form_processor', )
Python
from django.db import models class Tag(models.Model): name = models.CharField(max_length=200, unique=True) related_tags = models.ManyToManyField('self', blank=True, symmetrical=False, through='Tag_Relation') def rec_lookup(self, f, st): for obj in f(): st.add(obj) obj.rec_lookup(getattr(obj, f.__name__), st) def sub_types(self): return set([rel.source for rel in self.source_relation_set.all() if rel.is_a]) def super_types(self): return set([rel.target for rel in self.target_relation_set.all() if rel.is_a]) def sub_objects(self): return set([rel.target for rel in self.target_relation_set.all() if rel.has_a]) def super_objects(self): return set([rel.source for rel in self.source_relation_set.all() if rel.has_a]) def has_related_tags(self): return self.sub_types or self.super_types or self.sub_objects or self.super_objects def rec_sub_types(self): st = set([]) self.rec_lookup(self.sub_types, st) return st def rec_super_types(self): st = set([]) self.rec_lookup(self.super_types, st) return st def rec_sub_objects(self): st = set([]) self.rec_lookup(self.sub_objects, st) return st def rec_super_objects(self): st = set([]) self.rec_lookup(self.super_objects, st) return st def all_related_tags(self): return self.rec_sub_types() | self.rec_super_types() | self.rec_sub_objects() | self.rec_super_objects() def add_sub_type(self, sub_type): return Tag_Relation(source=sub_type, target=self, is_a=True) def add_super_type(self, super_type): return Tag_Relation(source=self, target=super_type, is_a=True) def add_sub_object(self, sub_object): return Tag_Relation(source=self, target=sub_object, has_a=True) def add_super_object(self, super_object): return Tag_Relation(source=super_object, target=self, has_a=True) def __unicode__(self): return self.name class Tag_Relation(models.Model): source = models.ForeignKey(Tag, related_name='target_relation_set') target = models.ForeignKey(Tag, related_name='source_relation_set') is_a = models.BooleanField(default=False); # True if source is a target has_a = models.BooleanField(default=False); # True if source has a target class Meta: unique_together = ("source", "target") def __unicode__(self): if self.is_a: return self.source.name + " is a type of " + self.target.name elif self.has_a: return self.source.name + " consists of " + self.target.name else: return "error"
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
from django.utils.encoding import force_unicode def parse_tags(tagstring): """ Parses tag input, with multiple word input being activated and delineated by commas and double quotes. Quotes take precedence, so they may contain commas. Returns a sorted list of unique tag names. Ported from Jonathan Buchanan's `django-tagging <http://django-tagging.googlecode.com/>`_ """ if not tagstring: return [] tagstring = force_unicode(tagstring) # Special case - if there are no commas or double quotes in the # input, we don't *do* a recall... I mean, we know we only need to # split on spaces. if u',' not in tagstring and u'"' not in tagstring: words = list(set(split_strip(tagstring, u' '))) words.sort() return words words = [] buffer = [] # Defer splitting of non-quoted sections until we know if there are # any unquoted commas. to_be_split = [] saw_loose_comma = False open_quote = False i = iter(tagstring) try: while True: c = i.next() if c == u'"': if buffer: to_be_split.append(u''.join(buffer)) buffer = [] # Find the matching quote open_quote = True c = i.next() while c != u'"': buffer.append(c) c = i.next() if buffer: word = u''.join(buffer).strip() if word: words.append(word) buffer = [] open_quote = False else: if not saw_loose_comma and c == u',': saw_loose_comma = True buffer.append(c) except StopIteration: # If we were parsing an open quote which was never closed treat # the buffer as unquoted. if buffer: if open_quote and u',' in buffer: saw_loose_comma = True to_be_split.append(u''.join(buffer)) if to_be_split: if saw_loose_comma: delimiter = u',' else: delimiter = u' ' for chunk in to_be_split: words.extend(split_strip(chunk, delimiter)) words = list(set(words)) words.sort() return words def split_strip(string, delimiter=u','): """ Splits ``string`` on ``delimiter``, stripping each resulting string and returning a list of non-empty strings. Ported from Jonathan Buchanan's `django-tagging <http://django-tagging.googlecode.com/>`_ """ if not string: return [] words = [w.strip() for w in string.split(delimiter)] return [w for w in words if w] def edit_string_for_tags(tags): """ Given list of ``Tag`` instances, creates a string representation of the list suitable for editing by the user, such that submitting the given string representation back without changing it will give the same list of tags. Tag names which contain commas will be double quoted. If any tag name which isn't being quoted contains whitespace, the resulting string of tag names will be comma-delimited, otherwise it will be space-delimited. Ported from Jonathan Buchanan's `django-tagging <http://django-tagging.googlecode.com/>`_ """ names = [] for tag in tags: name = tag.name if u',' in name or u' ' in name: names.append('"%s"' % name) else: names.append(name) return u', '.join(sorted(names))
Python
# Create your views here.
Python
import settings def GetGenericAvatarImgURL(): return settings.MEDIA_URL + 'images/generic.jpg' def GetGenericFoodImgURL(): return settings.MEDIA_URL + 'images/common/missingfoodpicture.jpg'
Python
from datetime import datetime from django.db import models, IntegrityError, transaction from django.contrib.gis.db import models from django.contrib.auth.models import User from django.template.defaultfilters import slugify from imagekit.models import ImageModel class NameSlugModel(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(unique=True, editable=False) class Meta: abstract = True def save(self, *args, **kwargs): """ Based on the Tag save() method in django-taggit, this method simply stores a slugified version of the name, ensuring that the unique constraint is observed """ self.slug = slug = slugify(self.name) i = 0 while True: try: savepoint = transaction.savepoint() res = super(NameSlugModel, self).save(*args, **kwargs) transaction.savepoint_commit(savepoint) return res except IntegrityError: transaction.savepoint_rollback(savepoint) i += 1 self.slug = '%s_%d' % (slug, i) class DateAwareModel(models.Model): modified_date = models.DateTimeField(auto_now=True) created_date = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class MyImageModel(ImageModel, NameSlugModel, DateAwareModel): image = models.ImageField(upload_to='images') num_views = models.PositiveIntegerField(editable=False, default=0) class IKOptions: spec_module = 'kokoomi.reviews.specs' cache_dir = 'cache' image_field = 'image' save_count_as = 'num_views' admin_thumbnail_spec = 'thumbnail' class Meta: abstract = True def __unicode__(self): return self.slug class UserOwnedModel(models.Model): user = models.ForeignKey(User) class Meta: abstract = True
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
# Create your views here.
Python
""" Serialize data to/from JSON """ from django.utils import simplejson from python import Serializer as PythonSerializer from django.core.serializers.json import Deserializer as JSONDeserializer, \ DjangoJSONEncoder class Serializer(PythonSerializer): """ Convert a queryset to JSON. """ def end_serialization(self): """Output a JSON encoded queryset.""" self.options.pop('stream', None) self.options.pop('fields', None) self.options.pop('excludes', None) self.options.pop('relations', None) self.options.pop('extras', None) self.options.pop('use_natural_keys', None) simplejson.dump(self.objects, self.stream, cls=DjangoJSONEncoder, **self.options) def getvalue(self): """ Return the fully serialized queryset (or None if the output stream is not seekable). """ if callable(getattr(self.stream, 'getvalue', None)): return self.stream.getvalue() Deserializer = JSONDeserializer
Python
""" Full Python serializer for Django. """ import base from django.utils.encoding import smart_unicode, is_protected_type from django.core.serializers.python import Deserializer as PythonDeserializer from django.db import models class Serializer(base.Serializer): """ Python serializer for Django modelled after Ruby on Rails. Default behaviour is to serialize only model fields with the exception of ForeignKey and ManyToMany fields which must be explicitly added in the ``relations`` argument. """ def __init__(self, *args, **kwargs): """ Initialize instance attributes. """ self._fields = None self._extras = None self.objects = [] super(Serializer, self).__init__(*args, **kwargs) def start_serialization(self): """ Called when serializing of the queryset starts. """ self._fields = None self._extras = None self.objects = [] def end_serialization(self): """ Called when serializing of the queryset ends. """ pass def start_object(self, obj): """ Called when serializing of an object starts. """ self._fields = {} self._extras = {} def end_object(self, obj): """ Called when serializing of an object ends. """ self.objects.append({ "model" : smart_unicode(obj._meta), "pk" : smart_unicode(obj._get_pk_val(), strings_only=True), "fields" : self._fields }) if self._extras: self.objects[-1]["extras"] = self._extras self._fields = None self._extras = None def handle_field(self, obj, field): """ Called to handle each individual (non-relational) field on an object. """ value = field._get_val_from_obj(obj) # Protected types (i.e., primitives like None, numbers, dates, # and Decimals) are passed through as is. All other values are # converted to string first. if is_protected_type(value): self._fields[field.name] = value else: self._fields[field.name] = field.value_to_string(obj) def handle_fk_field(self, obj, field): """ Called to handle a ForeignKey field. Recursively serializes relations specified in the 'relations' option. """ fname = field.name related = getattr(obj, fname) if related is not None: if fname in self.relations: # perform full serialization of FK serializer = Serializer() options = {} if isinstance(self.relations, dict): if isinstance(self.relations[fname], dict): options = self.relations[fname] self._fields[fname] = serializer.serialize([related], **options)[0] else: # emulate the original behaviour and serialize the pk value if self.use_natural_keys and hasattr(related, 'natural_key'): related = related.natural_key() else: if field.rel.field_name == related._meta.pk.name: # Related to remote object via primary key related = related._get_pk_val() else: # Related to remote object via other field related = smart_unicode(getattr(related, field.rel.field_name), strings_only=True) self._fields[fname] = related else: self._fields[fname] = smart_unicode(related, strings_only=True) def handle_m2m_field(self, obj, field): """ Called to handle a ManyToManyField. Recursively serializes relations specified in the 'relations' option. """ if field.rel.through._meta.auto_created: fname = field.name if fname in self.relations: # perform full serialization of M2M serializer = Serializer() options = {} if isinstance(self.relations, dict): if isinstance(self.relations[fname], dict): options = self.relations[fname] self._fields[fname] = [ serializer.serialize([related], **options)[0] for related in getattr(obj, fname).iterator()] else: # emulate the original behaviour and serialize to a list of # primary key values if self.use_natural_keys and hasattr(field.rel.to, 'natural_key'): m2m_value = lambda value: value.natural_key() else: m2m_value = lambda value: smart_unicode( value._get_pk_val(), strings_only=True) self._fields[fname] = [m2m_value(related) for related in getattr(obj, fname).iterator()] def getvalue(self): """ Return the fully serialized queryset (or None if the output stream is not seekable). """ return self.objects def handle_related_m2m_field(self, obj, field_name): """Called to handle 'reverse' m2m RelatedObjects Recursively serializes relations specified in the 'relations' option. """ fname = field_name if field_name in self.relations: # perform full serialization of M2M serializer = Serializer() options = {} if isinstance(self.relations, dict): if isinstance(self.relations[field_name], dict): options = self.relations[field_name] self._fields[fname] = [ serializer.serialize([related], **options)[0] for related in getattr(obj, fname).iterator()] else: pass # we don't really want to do this to reverse relations unless # explicitly requested in relations option # # emulate the original behaviour and serialize to a list of ids # self._fields[fname] = [ # smart_unicode(related._get_pk_val(), strings_only=True) # for related in getattr(obj, fname).iterator()] def handle_related_fk_field(self, obj, field_name): """Called to handle 'reverse' fk serialization.""" """ Called to handle a ForeignKey field. Recursively serializes relations specified in the 'relations' option. """ fname = field_name related = getattr(obj, fname) if related is not None: if field_name in self.relations: # perform full serialization of FK serializer = Serializer() options = {} if isinstance(self.relations, dict): if isinstance(self.relations[field_name], dict): options = self.relations[field_name] # Handle reverse foreign key lookups that recurse on the model if isinstance(related, models.Manager): # Related fields arrive here as querysets not modelfields self._fields[fname] = serializer.serialize(related.all(), **options) else: self._fields[fname] = serializer.serialize([related], **options)[0] else: pass # we don't really want to do this to reverse relations unless # explicitly requested in relations option # # emulate the original behaviour and serialize to a list of ids # self._fields[fname] = [ # smart_unicode(related._get_pk_val(), strings_only=True) # for related in getattr(obj, fname).iterator()] else: self._fields[fname] = smart_unicode(related, strings_only=True) def handle_extra_field(self, obj, field): """ Return "extra" fields that the user specifies. Can be a property or callable that takes no arguments. """ if hasattr(obj, field): extra = getattr(obj, field) if callable(extra): self._extras[field] = smart_unicode(extra(), strings_only=True) else: self._extras[field] = smart_unicode(extra, strings_only=True) Deserializer = PythonDeserializer
Python
"""New base serializer class to handle full serialization of model objects.""" try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.core.serializers import base class Serializer(base.Serializer): """Serializer for Django models inspired by Ruby on Rails serializer. """ def __init__(self, *args, **kwargs): """Declare instance attributes.""" self.options = None self.stream = None self.fields = None self.excludes = None self.relations = None self.extras = None self.use_natural_keys = None super(Serializer, self).__init__(*args, **kwargs) def serialize(self, queryset, **options): """Serialize a queryset with the following options allowed: fields - list of fields to be serialized. If not provided then all fields are serialized. excludes - list of fields to be excluded. Overrides ``fields``. relations - list of related fields to be fully serialized. extras - list of attributes and methods to include. Methods cannot take arguments. """ self.options = options self.stream = options.get("stream", StringIO()) self.fields = options.get("fields", []) self.excludes = options.get("excludes", []) self.relations = options.get("relations", []) self.extras = options.get("extras", []) self.use_natural_keys = options.get("use_natural_keys", False) self.start_serialization() for obj in queryset: self.start_object(obj) for field in obj._meta.local_fields: attname = field.attname if field.serialize: if field.rel is None: if attname not in self.excludes: if not self.fields or attname in self.fields: self.handle_field(obj, field) else: if attname[:-3] not in self.excludes: if not self.fields or attname[:-3] in self.fields: self.handle_fk_field(obj, field) for field in obj._meta.many_to_many: if field.serialize: if field.attname not in self.excludes: if not self.fields or field.attname in self.fields: self.handle_m2m_field(obj, field) related_fk_objects = obj._meta.get_all_related_objects() for ro in related_fk_objects: field_name = ro.get_accessor_name() if field_name not in self.excludes: self.handle_related_fk_field(obj, field_name) related_m2m_objects = obj._meta.get_all_related_many_to_many_objects() for ro in related_m2m_objects: field_name = ro.get_accessor_name() if field_name not in self.excludes: self.handle_related_m2m_field(obj, field_name) for extra in self.extras: self.handle_extra_field(obj, extra) self.end_object(obj) self.end_serialization() return self.getvalue() def handle_related_m2m_field(self, obj, field_name): """Called to handle 'reverse' m2m serialization.""" raise NotImplementedError def handle_related_fk_field(self, obj, field_name): """Called to handle 'reverse' fk serialization.""" raise NotImplementedError def handle_extra_field(self, obj, extra): """Called to handle 'extras' field serialization.""" raise NotImplementedError
Python
__version__ = '1.0.0'
Python
from django.db import models # Create your models here.
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('misc.views', (r'^about/', 'about'), )
Python
from django.http import Http404, HttpResponseRedirect, HttpResponse from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.auth import logout, login, authenticate from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.contrib.auth.views import password_change, password_change_done from django.db import models from profile.models import ProfileImage, UserProfile from profile.forms import UploadProfilePhotoForm, EditProfileInfoForm from datetime import datetime from common import globalvars import urllib, re, settings def about(request): variables = RequestContext(request, { }) return render_to_response('misc/about.html', variables)
Python
#!/usr/bin/env python from django.core.management import execute_manager import sys try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
from django.db import models # Create your models here.
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('accounts.views', # Example: # (r'^dishpop/', include('dishpop.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^user/(?P<user_name>\w+)/account/$', 'account'), (r'^user/(?P<user_name>\w+)/account/password_change$', 'change_password'), )
Python
from django.http import Http404, HttpResponseRedirect, HttpResponse from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.auth import logout, login, authenticate from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import PasswordChangeForm from datetime import datetime def GetUser(user_name): try: return User.objects.get(username=user_name) except User.DoesNotExist: raise Http404('Requested user not found.') @login_required def account(request, user_name): user = GetUser(user_name) variables = RequestContext(request, { 'user_public' : user, }) return render_to_response('registration/account.html', variables) def change_password(request, user_name): if request.method == 'POST': form = PasswordChangeForm(user=request.user, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/user/'+ user_name + '/') else: form = PasswordChangeForm(user=request.user) variables = RequestContext(request, { 'form': form }) return render_to_response('registration/password_change.html', variables)
Python
from django import forms from django.forms import ModelForm from reviews.models import DishImage, Dish import re from django.contrib.auth.models import User RATING_CHOICES = ( ('1', '1 Horrible'), ('2', '2 Poor'), ('3', '3 Just ok'), ('4', '4 Good'), ('5', '5 Excellent'), ) class BulkAddPlacesForm(forms.Form): file = forms.FileField() class SearchForm(forms.Form): query = forms.CharField(initial='What kind of food?', max_length=50, widget=forms.TextInput(attrs={'class':'shadow rounded'})) location = forms.CharField(initial='Where to look?', max_length=50, widget=forms.TextInput(attrs={'class':'shadow rounded'})) class UploadDishPhotoForm(ModelForm): class Meta: model = DishImage exclude = ('dish', 'user',) class EditTagsForm(forms.Form): dish_id = forms.IntegerField(widget=forms.HiddenInput, required=True) tags = forms.CharField(max_length=100, required=False) # this is currently used for adding new dish AND adding a review... class ReviewForm(forms.Form): name = forms.CharField() place = forms.CharField() tags = forms.CharField(required=False) text = forms.CharField(widget=forms.Textarea, required=False) rating = forms.ChoiceField(choices=RATING_CHOICES) review_id = forms.IntegerField(widget=forms.HiddenInput, required=False) class AddDishForm(ModelForm): class Meta: model = Dish fields = ('name', 'tags') class QuickReviewForm(forms.Form): text = forms.CharField(widget=forms.Textarea(attrs={'class':'quick_review'}), required=True, initial='Write stuff here') class RegistrationForm(forms.Form): username = forms.CharField(label=u'Username', max_length=30) password1 = forms.CharField( label=u'Password', widget=forms.PasswordInput() ) email = forms.EmailField(label=u'Email') def clean_username(self): username = self.cleaned_data['username'] if not re.search(r'^\w+$', username): raise forms.ValdiationError('Username can only contain ' 'alphanumeric characters and the underscore.') try: User.objects.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError('Username is already taken.')
Python
from imagekit.specs import ImageSpec from imagekit import processors # first we define our thumbnail resize processor class ResizeThumb(processors.Resize): width = 130 height = 100 crop = True class ResizeMedium(processors.Resize): width = 375 height = 375 crop = True # now we define a display size resize processor class ResizeDisplay(processors.Resize): width = 600 class EnhanceMedium(processors.Adjustment): contrast = 1.2 sharpness = 1.1 # now lets create an adjustment processor to enhance the image at small sizes class EnchanceThumb(processors.Adjustment): contrast = 1.2 sharpness = 1.1 class MediumDisplay(ImageSpec): pre_cache = True processors = [ResizeMedium, EnhanceMedium] # now we can define our thumbnail spec class Thumbnail(ImageSpec): #access_as = 'thumbnail_image' pre_cache = True processors = [ResizeThumb, EnchanceThumb] # and our display spec class Display(ImageSpec): increment_count = True processors = [ResizeDisplay]
Python
from datetime import datetime from django.contrib.gis.db import models from django.contrib.auth.models import User from tagging.models import Tag from common.models import NameSlugModel, DateAwareModel, MyImageModel, UserOwnedModel class PlaceManager(models.GeoManager): def get_by_natural_key(self, name, slug): return self.get(name=name, slug=slug) class Place(NameSlugModel, DateAwareModel): address1 = models.TextField(blank=True) address2 = models.TextField(blank=True) city = models.TextField(blank=True) state = models.TextField(blank=True) zip = models.TextField(blank=True) website = models.TextField(blank=True) geometry = models.PointField(srid=4326, blank=True) objects = PlaceManager() phone_number = models.CharField(max_length=30, blank=True) def natural_key(self): lat, lng = self.get_lat_lng() return { 'name' : self.name, #.replace("'", " & # 8 s "), 'slug' : self.slug, 'lat' : lat, 'lng' : lng } def get_lat_lng(self): # assuming geometry has 'POINT (38.23323 28.238923)' format return str(self.geometry).lstrip('POINT (').rstrip(')').split() def __unicode__(self): return self.name class Dish(NameSlugModel, DateAwareModel): # for lists only last_added_date_time = models.DateTimeField(blank=True, null=True) last_added_to = models.IntegerField(blank=True, null=True) # for orders only last_sorted_date_time = models.DateTimeField(blank=True, null=True) last_sorted_in = models.IntegerField(blank=True, null=True) # required because place is a geo field objects = models.GeoManager() place = models.ForeignKey(Place) tags = models.ManyToManyField(Tag, blank=True) # used by view to include thumbnail url in JSON serialization def get_thumbnail_url(self): if self.dishimage_set.all(): return self.dishimage_set.all()[0].thumbnail.url return '' # used by view to include display view url in JSON serialization def medium_img_url(self): if self.dishimage_set.all(): return self.dishimage_set.all()[0].mediumdisplay.url return '' # used because i'm not sure why sometimes apostrophes messed up JSON and sometimes don't... def get_place_name(self): return self.place.name def natural_key(self): return { 'name' : self.name, #.replace("'", " & # 8 s "), 'place_name' : self.place.name, #.replace("'", " & # 8 s "), 'id' : self.id, } class Meta: verbose_name_plural = ('dishes') def __unicode__(self): return self.name class PlaceImage(MyImageModel, UserOwnedModel): place = models.ForeignKey(Place) class DishImage(MyImageModel, UserOwnedModel): dish = models.ForeignKey(Dish) def get_thumbnail_url(self): return self.thumbnail.url
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
from django.core import serializers def serialize_dishes(dishes, user): # if (user.is_authenticated()): # for d in dishes: # d.set_user_dependent_flags(user) return serializers.serialize('json', dishes, extras=('get_thumbnail_url', 'medium_img_url', 'is_liked_by_curr_user', 'is_disliked_by_curr_user', 'is_okd_by_curr_user', 'get_place_name'), relations=('dishimage_set',), use_natural_keys=True) def serialize_ranks(ranks): return serializers.serialize('json', ranks, use_natural_keys=True) # def serialize_reviews(reviews, user): # return serializers.serialize('json', reviews, extras=('get_user_profile_icon_url', 'get_username'), use_natural_keys=True) # extras must be list!!! i.e. add a comma after first string def serialize_dish_photos_urls(photos): return serializers.serialize('json', photos, extras=('get_thumbnail_url',), use_natural_keys=True)
Python
from django.conf.urls.defaults import * from reviews.api import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('reviews.views', # Example: # (r'^dishpop/', include('dishpop.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^$', 'home'), #(r'^action/(?P<action_string>[a-z]+)/dish/(?P<dish_id>\d+)/$', 'submit_preference_for_dish'), #(r'^user/(?P<user_name>\w+)/$', 'user_page'), (r'^t/(?P<tag_name>[a-z0-9-]+)/$', 'tag'), (r'^p/(?P<place_slug>[a-z0-9-]+)/$', 'place'), (r'^p/(?P<place_id>\d+)/add_dish/$', 'add_dish'), (r'^p/(?P<place_id>\d+)/add_dish/name_check/$', 'dish_name_check'), (r'^d/(?P<dish_id>\d+)$', 'dish'), (r'^d/(?P<dish_slug>[a-z0-9-]+)$', 'dish_page'), # (r'^place/(?P<place_slug>[a-z0-9-]+)/$', 'place'), (r'^submit/dish/$', 'submit_dish'), (r'^submit/photo/dish/(?P<dish_id>\d+)/$', 'add_photo'), (r'^submit/tags/dish/(?P<dish_id>\d+)/$', 'submit_tags'), # (r'^submit/review/dish/(?P<dish_id>\d+)/$', 'submit_review'), (r'^submit/review/dish/$', 'submit_dish'), (r'^submit/ranking/$', 'submit_ranking'), # (r'^delete/$', 'delete_review_or_image'), (r'^search/$', 'search'), (r'^logout/$', 'log_user_out'), # api (r'^api/feed/d/(?P<dish_id>\d+)/$', get_feed), (r'^api/ranks/t/(?P<tag_id>\d+)/$', get_my_ranks), (r'^api/ranks/t/(?P<tag_id>\d+)/(?P<dish_id>\d+)/$', delete_rank), (r'^api/dishes/t/(?P<tag_id>\d+)/$', get_dishes_for_tag), (r'^api/photos/d/(?P<dish_id>\d+)/$', get_dish_photo_urls), )
Python
from django.conf.urls.defaults import * from django.contrib import admin from django.contrib.gis.geos import fromstr from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from geopy import geocoders from reviews.forms import BulkAddPlacesForm from reviews.models import Place, Dish, PlaceImage, DishImage from sorting.models import List, ListMembership, Sorting, Item, SortDelta from tagging.models import Tag, Tag_Relation class ImageAdmin(admin.ModelAdmin): list_display = ('admin_thumbnail_view',) class PlaceAdmin(admin.ModelAdmin): def get_urls(self): ''' Adding bulk upload view to admin site. ''' urls = super(PlaceAdmin, self).get_urls() my_urls = patterns('', (r'^add/bulk$', self.admin_site.admin_view(self.bulk_add_view)) ) return my_urls + urls def bulk_add_view(self, request): if request.method == 'POST': form = BulkAddPlacesForm(request.POST, request.FILES) if form.is_valid(): self.parse(request.FILES['file']) return HttpResponseRedirect('/admin/reviews/place') else: form = BulkAddPlacesForm() return render_to_response('reviews/bulkadd.html', {'form': form, 'current_app': self.admin_site.name}, context_instance=RequestContext(request)) def parse(self, f): g = geocoders.Google(resource='maps') ids = {} errors = [] curr_id = '' i = 0 # keep track of field count since we expect 15 fields to be parsed from each line addr = '' trunc = '' counter = 0 c = f.read(); #for chunk in f.chunks(): #c = str(chunk) while c: # do while c not empty a,b,c = c.partition(',') # if contains newline, partition at newline if a.find('\n') > -1: a,b2,c2 = a.partition('\n') c = c2 + ',' + c a = a.strip('"') a = a.strip(' ') if i is 0: if a in ids: _,_,c = c.partition('\n') continue # skip else: ids[a] = 1 curr_id = a elif i is 1: # name name = a elif i is 3: # building # addr = a elif i is 4: # street addr = addr + ' ' + a elif i is 5: # zipcode addr = addr + ' ' + a # geopy lookup # print addr try: place = addr lat, lng = 0, 0 #place,(lat,lng) = g.geocode(addr) addr = '' except: place = addr lat, lng = 0, 0 errors.append(curr_id) elif i is 6: # phone # phone_num = a elif i is 7: # cuisine code cuisine_code = i elif i is 14: # start over print phone_num place = Place(name=name, cuisine_code=cuisine_code, geometry=fromstr('POINT('+str(lat)+' '+str(lng)+')',srid=4326), phone_number = phone_num) place.save() print str(counter) + name counter = counter + 1 # print 'Created ' + name # print 'i: ' + str(i) # print 'a: ' + a # print 'b: ' + b # print 'c: ' + c i = -1 # print i i = i + 1 # if not c and i > 0: # trunc = print 'ERRORS: ' + errors class TagsInline(admin.TabularInline): model = Dish.tags.through extra = 1 class ImageInline(admin.TabularInline): model = DishImage extra = 1 class ItemInline(admin.StackedInline): model = Item extra = 1 class DishAdmin(admin.ModelAdmin): list_display = ('name', 'place') inlines = [ TagsInline, ImageInline, ItemInline, ] exclude = ('tags',) class TagAdmin(admin.ModelAdmin): inlines = [ TagsInline, ] admin.site.register(Place, PlaceAdmin) admin.site.register(Dish, DishAdmin) admin.site.register(PlaceImage, ImageAdmin) admin.site.register(DishImage, ImageAdmin) admin.site.register(Tag, TagAdmin) admin.site.register(Tag_Relation)
Python
from django.http import Http404, HttpResponseRedirect, HttpResponse from django.template import RequestContext from django.contrib.auth import logout, login, authenticate from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import PasswordChangeForm from django.contrib.gis.geos import fromstr from django.contrib.gis.measure import D # D is a short for Distance from django.db.models import Q from django.shortcuts import render_to_response, get_object_or_404 from django.utils import simplejson from reviews.models import Dish, Place, DishImage from reviews.forms import ReviewForm, RegistrationForm, UploadDishPhotoForm, SearchForm, EditTagsForm, QuickReviewForm, AddDishForm from reviews.serialization_helpers import * from sorting.models import SortDelta from tagging.models import Tag from tagging.utils import parse_tags, edit_string_for_tags from datetime import datetime @login_required def submit_ranking(request): try: if request.is_ajax(): # print 'Raw Data: "%s"' % request.raw_post_data json_data = simplejson.loads(request.raw_post_data) myTag = Tag.objects.get(id=json_data['tagId']) newRanking, created = Ranking.objects.get_or_create(tag=myTag, user=request.user) # print 'here' idx = 1 for dishId in json_data['ranking']: dish = Dish.objects.get(id=dishId) rank, created = Rank.objects.get_or_create(dish=dish, ranking=newRanking) if json_data['text'][idx-1]: print json_data['text'][idx-1] rank.comment = json_data['text'][idx-1].strip() else: rank.comment = "" rank.rank = idx print rank.comment rank.save() # print 'after save' idx = idx + 1 return HttpResponse('Success'); except: return HttpResponse('Fail'); def register_page(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = User.objects.create_user( username = cd['username'].lower(), password = cd['password1'], email = cd['email'] ) # automagically log user in user = authenticate(username = cd['username'].lower(), password = cd['password1']) login(request, user) return HttpResponseRedirect('/') else: form = RegistrationForm() variables = RequestContext(request, { 'form': form }) return render_to_response('registration/register.html', variables) def log_user_out(request): logout(request) return HttpResponseRedirect('/') def user_page(request, user_name): try: user = User.objects.get(username=user_name) except User.DoesNotExist: raise Http404('Requested user not found.') variables = RequestContext(request, { 'user_public' : user, 'show_edit' : user_name == request.user.username, }) return render_to_response('reviews/user_page.html', variables) def home(request): dishes = Dish.objects.order_by('-created_date') id_dish = [(d.id, d) for d in dishes] variables = RequestContext(request, { 'id_dish_coll': id_dish, 'dishes_json': serialize_dishes(dishes, request.user), }) # tags = Tag.objects.all().order_by('name') # td = [] # for tag in tags: # td.append(( tag, # Dish.objects.filter(rank__ranking__tag__id=tag.id).filter(rank__ranking__user__username="kokoomi").order_by('-rank') )) # dut = [] # for tag, dishes in td: # tmp_dut = [] # for dish in dishes: # print dish.last_sorted_user_id # # REMEMBER TO CHECK IF DISH HAS BEEN RANKED # tmp_dut.append(( dish, User.objects.get(id=dish.last_sorted_user_id), dish.last_sorted_date_time )) # dut.append(( tag, tmp_dut )) # # find recent diffs and display.. # variables = RequestContext(request, { # 'td': dut, # }) return render_to_response('reviews/main_page.html', variables) def search(request): dishes = Dish.objects.all() if 'query' in request.GET: query = request.GET['query'].strip() if query: form = SearchForm({'query' : query}) dishes = dishes.filter(name__icontains=query) if 'lat' in request.GET and 'lng' in request.GET: # filter dishes based on lat, lng lat = request.GET['lat'].strip() lng = request.GET['lng'].strip() if lat and lng: # need to populate form with search value like above pnt = fromstr('POINT(' + lat + ' ' + lng + ')', srid=4326) # filter dishes that are within D distance from pnt and attach a distance attribute dishes = dishes.filter(place__geometry__distance_lte=(pnt, D(mi=10))).distance(pnt, field_name='place__geometry') variables = RequestContext(request, { 'dishes_json': serialize_dishes(dishes, request.user), 'show_edit' : request.user.is_authenticated(), 'isMapsView': 1 }) if request.GET.has_key('ajax'): return HttpResponse(variables['dishes_json'], mimetype='application/javascript') #return render_to_response('reviews/dish_list.html', variables) else: return render_to_response('reviews/search_page.html', variables) # def tag(request, tag_id): # '''List all the dishes associated with the specified tag.''' # tag = get_object_or_404(Tag, id=tag_id) # related_tags = tag.all_related_tags() # return render_to_response('reviews/tag.html', RequestContext(request, {'tag' : tag, 'related_tags' : related_tags})) @login_required def submit_tags(request, dish_id): dish = get_object_or_404(Dish, id=dish_id) ajax = 'ajax' in request.GET initial_data = {} if request.method == 'POST': form = EditTagsForm(request.POST) if form.is_valid(): cd = form.cleaned_data # parse tags and add to dish # what if users are stupid and tag dishes badly? tag_string = cd['tags'] tag_list = parse_tags(tag_string) #tag_obj_list = [] dish.tags.clear() for tag in tag_list: tag_obj, dummy = Tag.objects.get_or_create(name = tag) #tag_obj_list.append(tag_obj) if not tag_obj in dish.tags.all(): dish.tags.add(tag_obj) if ajax: variables = RequestContext(request, { 'dish': dish, 'show_edit': request.user.is_authenticated(), }) return render_to_response( 'reviews/tag_list.html', variables ) return HttpResponseRedirect('/dish/' + str(dish.id)) else: if ajax: return HttpResponse(u'failure') tags_string = edit_string_for_tags(dish.tags.all()) initial_data['tags'] = tags_string initial_data['dish_id'] = dish_id form = EditTagsForm( initial = initial_data ) if ajax: return render_to_response('reviews/edit_tags_form.html', {'form': form}, context_instance=RequestContext(request)) return render_to_response('reviews/submit_form_page.html', {'form': form}, context_instance=RequestContext(request)) def add_dish(request, place_id): f = AddDishForm(request.POST) if f.is_valid(): new_dish = f.save(commit=False) new_dish.place = get_object_or_404(Place, id=place_id) new_dish.save() f.save_m2m() return HttpResponse(u'Success') return HttpResponse(u'Failure') def dish_name_check(request, place_id): d = Dish.objects.filter(name__iexact=request.GET['name'].strip(), place__id=place_id) if d: return HttpResponse(u'invalid') return HttpResponse(u'valid') def place(request, place_slug): dishes = Dish.objects.order_by('-created_date') id_dish = [(d.id, d) for d in dishes] place = get_object_or_404(Place, slug=place_slug) variables = RequestContext(request, { 'id_dish_coll': id_dish, 'place' : place, 'add_dish_form' : AddDishForm(), 'dishes_json': serialize_dishes(dishes, request.user), }) return render_to_response('reviews/place.html', variables) def tag(request, tag_name): tag = get_object_or_404(Tag, slug=tag_name) dishes = tag.dish_set.all() #reviews = Rank.objects.filter(~Q(comment = "")) #rankings = Ranking.objects.filter(tag__name__iexact=tag_name) variables = RequestContext(request, { 'tag_id' : tag.id, 'tag' : tag, 'dishes' : dishes, 'dishes_json': serialize_dishes(dishes, request.user), #'num_dishes': len(dishes), #'num_reviews': len(reviews), #'num_ranks': len(rankings), #'show_edit' : request.user.is_authenticated(), #'isMapsView': 1, #'shouldDisplayNames': 1 }) return render_to_response('reviews/tag.html', variables) def dish(request, dish_id): '''List all the reviews for the given dish''' d = get_object_or_404(Dish, id=dish_id) variables = RequestContext(request, { 'dish' : d, }) return render_to_response('reviews/dish.html', variables) def dish_page(request, dish_slug): '''List all the reviews for the given dish''' d = get_object_or_404(Dish, slug=dish_slug) variables = RequestContext(request, { 'dish' : d, }) return render_to_response('reviews/dish_page.html', variables) @login_required def add_photo(request, dish_id): if dish_id: dish = get_object_or_404(Dish, id=dish_id) if request.method == 'POST': form = UploadDishPhotoForm(request.POST, request.FILES) if form.is_valid(): new_dish_image = form.save(commit=False) new_dish_image.dish = dish new_dish_image.user = request.user new_dish_image.save() return HttpResponseRedirect('/dish/' + str(dish.id)) else: form = UploadDishPhotoForm() return render_to_response('reviews/upload.html', {'form': form}, context_instance=RequestContext(request)) @login_required def submit_dish(request): dish_id = None if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): cd = form.cleaned_data placename = cd['place'] place, dummy = Place.objects.get_or_create(name = placename) dish, dummy = Dish.objects.get_or_create(name = cd['name'], place = place) dish_id = dish.id return submit_review(request, dish_id) else: initial_data = {'text': 'Write stuff here.'} form = ReviewForm(initial = initial_data) return render_to_response('reviews/submit_form_page.html', {'form': form}, context_instance=RequestContext(request)) @login_required def submit_tags(request, dish_id): dish = get_object_or_404(Dish, id=dish_id) ajax = 'ajax' in request.GET initial_data = {} if request.method == 'POST': form = EditTagsForm(request.POST) if form.is_valid(): cd = form.cleaned_data # parse tags and add to dish # what if users are stupid and tag dishes badly? tag_string = cd['tags'] tag_list = parse_tags(tag_string) #tag_obj_list = [] dish.tags.clear() for tag in tag_list: tag_obj, dummy = Tag.objects.get_or_create(name = tag) #tag_obj_list.append(tag_obj) if not tag_obj in dish.tags.all(): dish.tags.add(tag_obj) if ajax: variables = RequestContext(request, { 'dish': dish, 'show_edit': request.user.is_authenticated(), }) return render_to_response( 'reviews/tag_list.html', variables ) return HttpResponseRedirect('/dish/' + str(dish.id)) else: if ajax: return HttpResponse(u'failure') tags_string = edit_string_for_tags(dish.tags.all()) initial_data['tags'] = tags_string initial_data['dish_id'] = dish_id form = EditTagsForm( initial = initial_data ) if ajax: return render_to_response('reviews/edit_tags_form.html', {'form': form}, context_instance=RequestContext(request)) return render_to_response('reviews/submit_form_page.html', {'form': form}, context_instance=RequestContext(request)) # @login_required # def delete_review_or_image(request): # if 'review_id' in request.GET: # review_id = request.GET['review_id'] # review = get_object_or_404(Review, id=review_id) # review.delete() # elif 'photo_id' in request.GET: # photo_id = request.GET['photo_id'] # photo = get_object_or_404(DishImage, id=photo_id) # photo.delete() # return HttpResponseRedirect('/user/' + str(request.user.username)) # @login_required # def submit_review(request, dish_id): # dish = get_object_or_404(Dish, id=dish_id) # initial_data = {} # if request.method == 'POST': # form = QuickReviewForm(request.POST) # if form.is_valid(): # cd = form.cleaned_data # review = Review.objects.create(text = cd['text'], # dish = dish, # user = request.user) # dish.review_set.add(review) # return HttpResponse(serialize_dishes([dish], request.user), mimetype='application/javascript') # else: # initial_data['text'] = 'Write stuff here.' # form = QuickReviewForm( # initial = initial_data # ) # return render_to_response('reviews/quick_review_template.html', {'form': form}, # context_instance=RequestContext(request)) # @login_required # def submit_review(request, dish_id): # dish = get_object_or_404(Dish, id=dish_id) # initial_data = {} # if request.method == 'POST': # form = ReviewForm(request.POST) # if form.is_valid(): # cd = form.cleaned_data # if 'review_id' in cd and cd['review_id']: # review_id = cd['review_id'] # review = Review.objects.get(id = review_id) # review.text = cd['text'] # review.rating = cd['rating'] # else: # review = Review.objects.create(text = cd['text'], # dish = dish, # user = request.user, # rating = cd['rating']) # # parse tags and add to dish # # what if users are stupid and tag dishes badly? # tag_string = cd['tags'] # tag_list = parse_tags(tag_string) # for tag in tag_list: # tag_obj, dummy = Tag.objects.get_or_create(name = tag) # tag_obj.review_set.add(review) # if not tag_obj in dish.tags.all(): # dish.tags.add(tag_obj) # dish.review_set.add(review) # return HttpResponseRedirect('/dish/' + str(dish.id)) # elif 'review_id' in request.GET: # case for editing an existing review # review_id = request.GET['review_id'] # try: # review = Review.objects.get(id = review_id) # tags_string = edit_string_for_tags(review.tags.all()) # initial_data['tags'] = tags_string # initial_data['text'] = review.text # initial_data['rating'] = review.rating # initial_data['review_id'] = review.id # except (Review.DoesNotExist): # pass # else: # case for new review # initial_data['text'] = 'Write stuff here.' # initial_data['name'] = dish.name # initial_data['place'] = dish.place # form = ReviewForm( # initial = initial_data # ) # return render_to_response('reviews/submit_form_page.html', {'form': form}, # context_instance=RequestContext(request)) # def add_dish(request): # #dish = get_object_or_404(Dish, id=dish_id) # if request.method == 'POST': # form = NewDishForm(request.POST) # if form.is_valid(): # cd = form.cleaned_data # dish = Dish.objects.create(name = cd['name'], # place = cd['place']) # review.save() # return HttpResponseRedirect('/') # else: # form = ReviewForm( # initial = {'text': 'Write stuff here.'} # ) # return render_to_response('reviews/review.html', {'form': form, 'dish': dish}, # context_instance=RequestContext(request)) # def add_review(request, dish_id): # dish = get_object_or_404(Dish, id=dish_id) # try: # review = Review.objects.create(text=str(request.POST['review_text']), dish=dish) # except (KeyError): # # Redisplay the review form. # return render_to_response('reviews/review.html', { # 'dish': dish, # 'error_message': "You didn't seleAdasdfasfct a choice.", # }, context_instance=RequestContext(request)) # else: # review.save() # # Always return an HttpResponseRedirect after successfully dealing # # with POST data. This prevents data from being posted twice if a # # user hits the Back button. # return HttpResponseRedirect(reverse('reviews.views.dish', args=(dish.id,)))
Python
from django.http import HttpResponse from reviews.models import Dish, DishImage from reviews.serialization_helpers import * from tagging.models import Tag def get_feed(request, dish_id): try: feed_items = Rank.objects.filter(dish__id__exact=dish_id).order_by('modified_date') # sorted(user_ranking.rank_set.all(), key=lambda rank: rank.rank) return HttpResponse(serialize_ranks(feed_items), mimetype='application/javascript') except: return HttpResponse('') def get_my_ranks(request, tag_id): try: ranks = Rank.objects.filter(ranking__tag__id__exact=tag_id) # myTag = Tag.objects.get(id=tag_id) # user_ranking = Ranking.objects.get(tag=myTag, user=request.user) # sorted(user_ranking.rank_set.all(), key=lambda rank: rank.rank) # ranks = sorted(user_ranking.rank_set.all(), key=lambda rank: rank.rank, reverse=True) return HttpResponse(serialize_ranks(ranks), mimetype='application/javascript') except: return HttpResponse('') def delete_rank(request, tag_id, dish_id): try: print tag_id print request.user print dish_id try: ranking = Ranking.objects.get(tag__id__exact=tag_id, user__exact=request.user) # print 'after ranking' rank = Rank.objects.get(ranking__tag__id__exact=tag_id, ranking__user__exact=request.user, dish__id__exact=dish_id) # print 'after rank' rank.delete() if len(ranking.rank_set.all()) == 0: ranking.delete() return HttpResponse('Success') except: return HttpResponse('Rank does not exist') except DoesNotExist: return HttpResponse('Something went wrong...') def get_dishes_for_tag(request, tag_id): dishes = Dish.objects.filter(id=1) # orankings = Ranking.objects.filter(tag__id__exact=tag_id, user__username="kokoomi")[0] # sort orankings by rank, get dishes # dishes = [r.dish for r in sorted(orankings.rank_set.all(), key=lambda rank: rank.rank, reverse=False)] return HttpResponse(serialize_dishes(dishes, request.user), mimetype='application/javascript') def get_dish_photo_urls(request, dish_id): try: photos = DishImage.objects.filter(dish__id__exact=dish_id) return HttpResponse(serialize_dish_photos_urls(photos), mimetype='application/javascript') except: return HttpResponse('')
Python
from reviews.forms import SearchForm def add_search_form_processor(request): form = SearchForm() return {'search_form': form }
Python
from common.models import NameSlugModel, DateAwareModel, MyImageModel, UserOwnedModel from datetime import datetime from django.contrib.gis.db import models from django.db import models from reviews.models import Dish from tagging.models import Tag # Create your models here. class List(NameSlugModel, DateAwareModel, UserOwnedModel): dishes = models.ManyToManyField(Dish, blank=True, through='ListMembership') class ListMembership(DateAwareModel): dish = models.ForeignKey(Dish) list = models.ForeignKey(List) # def __unicode__(self): # return self.dish.name + ' ranked #' + str(self.rank) + ' in ' + str(self.ordering.tag.name) def save(self, *args, **kwargs): """ Used to update Dish object's last_added_to_list fields """ self.dish.last_added_to = self.list.id self.dish.last_added_date_time = datetime.now() self.dish.save() super(ListMembership, self).save(*args, **kwargs) class Sorting(DateAwareModel, UserOwnedModel): end_comment = models.TextField(max_length=5000, blank=True) dishes = models.ManyToManyField(Dish, through='Item') intro_comment = models.TextField(max_length=5000, blank=True) is_master = models.BooleanField(default=False) tag = models.ForeignKey(Tag) # def natural_key(self): # return { # 'username' : self.user.username, #.replace("'", " & # 8 s "), # 'tag' : self.tag.name, # 'id' : self.id, # 'count': len(self.rank_set.all()), # } def __init__(self, *args, **kw): print "Entering Sorting init..." super(Sorting, self).__init__(*args, **kw) # print "After super init..." if self.pk: self._old_sort_order = [d.id for d in self.dishes.all()] print "Init Old Sort Order: " + str(self._old_sort_order) self._empty_comment_indicator = [d.id for d in Dish.objects.filter(sorting=self, item__comment__exact='')] def save(self, *args, **kwargs): print "Entering Sorting save..." print "Init Sort Order: " + str([d.id for d in self.dishes.all()]) super(Sorting, self).save(*args, **kwargs) # print "After super save..." # isNew = False # if hasattr(self, '_old_sort_order'): # old_items = frozenset(self._old_sort_order) # else: # old_items = frozenset() # isNew = True # print "Arguments..." # for arg in args: # print arg # print "Keywords..." # for kw in kwargs.keys(): # print kw, ":", kwargs[kw] # new_items = frozenset([d.id for d in self.dishes.all()]) # print 'new: ' + str(new_items) # print 'old: ' + str(old_items) # added_items = new_items.difference(old_items) # print added_items # if hasattr(self, '_empty_comment_indicator'): # old_empty_comment_indicator = frozenset(self._empty_comment_indicator) # else: # old_empty_comment_indicator = frozenset() # new_empty_comment_indicator = frozenset([d.id for d in Dish.objects.filter(sorting=self, item__comment__exact='')]) # new_comments = new_empty_comment_indicator.difference(old_empty_comment_indicator) # if added_items or new_comments: # print 'Creating Sort Delta...' # s = SortDelta() # s.isNew = isNew # s.sorting = self # s.items_with_new_comment = ','.join(map(str, new_comments)) # s.items_added = ','.join(map(str, added_items)) # s.prev_order = ','.join(map(str, self._old_sort_order)) # s.new_order = ','.join([str(d.id) for d in self.dishes.all()]) # s.save() def __unicode__(self): return self.tag.name + ' sorting ' + '(' + self.user.username + ')' class Item(DateAwareModel): comment = models.TextField(max_length=5000, blank=True) dish = models.ForeignKey(Dish) sorting = models.ForeignKey(Sorting) preference = models.IntegerField() # 1 - bad, 2 - ok, 3 - good rank = models.IntegerField(default=1) def __unicode__(self): return self.dish.name + ' in ' + str(self.sorting.tag.name) class Meta: unique_together = ("dish", "sorting") ordering = ['-rank'] def save(self, *args, **kwargs): """ Used to update Dish object's last_sorted fields """ print "Entering Item save..." self.dish.last_sorted_in = self.sorting.id self.dish.last_sorted_date_time = datetime.now() self.dish.save() return super(Item, self).save(*args, **kwargs) class SortDelta(DateAwareModel): # calculated each time a sorting is modified sorting = models.ForeignKey(Sorting) # isNew = models.BooleanField(default=False) items_with_new_comment = models.CommaSeparatedIntegerField(max_length=1000, blank=True) items_added = models.CommaSeparatedIntegerField(max_length=1000, blank=True) prev_order = models.CommaSeparatedIntegerField(max_length=1000, blank=True) new_order = models.CommaSeparatedIntegerField(max_length=1000, blank=True)
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
from django.conf.urls.defaults import * from django.contrib import admin from sorting.models import List, ListMembership, Sorting, Item, SortDelta class ListMembershipInline(admin.StackedInline): model = ListMembership extra = 3 class ListAdmin(admin.ModelAdmin): inlines = [ ListMembershipInline, ] class ItemInline(admin.StackedInline): model = Item extra = 3 class SortingAdmin(admin.ModelAdmin): inlines = [ ItemInline, ] admin.site.register(List, ListAdmin) admin.site.register(Sorting, SortingAdmin) admin.site.register(SortDelta)
Python
# Create your views here.
Python
#!/usr/bin/env python from django.core.management import execute_manager import sys try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
from django.conf.urls.defaults import * import os # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() site_media = os.path.join(os.path.dirname(__file__), 'site_media') urlpatterns = patterns('', # Example: # (r'^kokoomi/', include('kokoomi.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^', include('reviews.urls')), (r'^', include('profile.urls')), (r'^', include('accounts.urls')), (r'^', include('misc.urls')), (r'^admin/', include(admin.site.urls)), (r'^login/$', 'django.contrib.auth.views.login'), (r'^register/$', 'reviews.views.register_page'), # consider moving this out (r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': site_media}), )
Python
from django import forms from django.forms import ModelForm, FileInput from django.contrib.auth.models import User from profile.models import ProfileImage, UserProfile class UploadProfilePhotoForm(ModelForm): class Meta: model = ProfileImage exclude = ('user', 'isPrimary', 'name') class EditProfileInfoForm(ModelForm): class Meta: model = UserProfile exclude = ('user', 'lists', 'bookmarks')
Python
from imagekit.specs import ImageSpec from imagekit import processors # first we define our thumbnail resize processor class ResizeThumb(processors.Resize): width = 100 height = 75 crop = True # now we define a display size resize processor class ResizeDisplay(processors.Resize): width = 190 # now lets create an adjustment processor to enhance the image at small sizes class EnchanceThumb(processors.Adjustment): contrast = 1.2 sharpness = 1.1 # now we can define our thumbnail spec class Thumbnail(ImageSpec): #access_as = 'thumbnail_image' pre_cache = True processors = [ResizeThumb, EnchanceThumb] # and our display spec class Display(ImageSpec): increment_count = True processors = [ResizeDisplay]
Python
from common.models import MyImageModel, UserOwnedModel, DateAwareModel from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from reviews.models import Dish from sorting.models import List class UserProfile(DateAwareModel): name = models.CharField(max_length=255) bookmarks = models.ForeignKey(Dish, blank=True, null=True) lists = models.ManyToManyField(List, blank=True, null=True) location = models.CharField(max_length=255, blank=True) user = models.OneToOneField(User) website = models.URLField(blank=True, verify_exists=False) def __unicode__(self): return str(self.user) class ProfileImage(MyImageModel): profile = models.ForeignKey(UserProfile) class IKOptions: # This inner class is where we define the ImageKit options for the model spec_module = 'kokoomi.profile.specs' cache_dir = 'images' image_field = 'image' save_count_as = 'num_views' class Connection(DateAwareModel): follower = models.ForeignKey(UserProfile, related_name='following') leader = models.ForeignKey(UserProfile, related_name='followers') def create_profile(sender, **kw): user = kw["instance"] if kw["created"]: profile = UserProfile(user=user) profile.save() post_save.connect(create_profile, sender=User, dispatch_uid="users-profilecreation-signal")
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('profile.views', # Example: # (r'^dishpop/', include('dishpop.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^user/(?P<user_name>\w+)/$', 'profile'), (r'^user/(?P<user_name>\w+)/profilepic$', 'upload_photo'), (r'^profile/edit$', 'edit_profile'), (r'^user/(?P<user_name>\w+)/profilepic/(?P<profileimg_id>\d+)/c$', 'change_photo'), (r'^user/(?P<user_name>\w+)/profilepic/(?P<profileimg_id>\d+)/d$', 'delete_photo'), )
Python
from django.contrib import admin from profile.models import UserProfile, ProfileImage, Connection # class ImageAdmin(admin.ModelAdmin): # list_display = ('name', 'admin_thumbnail_view',) # class PlaceAdmin(admin.ModelAdmin): # exclude = ('modified_date', 'created_date') # class DishAdmin(admin.ModelAdmin): # exclude = ('modified_date', 'created_date') class ProfileImageInline(admin.TabularInline): model = ProfileImage class FollowersInline(admin.TabularInline): model = Connection fk_name = 'leader' class FollowingInline(admin.TabularInline): model = Connection fk_name = 'follower' class UserProfileAdmin(admin.ModelAdmin): inlines = [ ProfileImageInline, FollowersInline, FollowingInline, ] admin.site.register(UserProfile, UserProfileAdmin) # admin.site.register(ProfileImage) # admin.site.register(Dish) # admin.site.register(PlaceImage, ImageAdmin) # admin.site.register(DishImage, ImageAdmin) # admin.site.register(Review) # admin.site.register(Tag) # admin.site.register(Tag_Relation)
Python
from django.http import Http404, HttpResponseRedirect, HttpResponse from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.auth import logout, login, authenticate from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.contrib.auth.views import password_change, password_change_done from django.db import models from profile.models import ProfileImage, UserProfile from profile.forms import UploadProfilePhotoForm, EditProfileInfoForm from datetime import datetime from common import globalvars import urllib, re, settings def GetDefaultImageUrl(user): if user.get_profile().profileimage_set.all().count() > 0: media_url = user.get_profile().profileimage_set.all()[0].mediumdisplay.url else: media_url = globalvars.GetGenericAvatarImgURL() return media_url @login_required def profile(request, user_name): user = request.user # globalvars.GetGenericFoodImgURL() variables = RequestContext(request, { 'user_public' : user, 'profile' : user.get_profile() }) return render_to_response('profile/profile.html', variables) @login_required def edit_profile(request): profile = request.user.get_profile() print profile.user if request.method == 'POST': form = EditProfileInfoForm(request.POST, request.FILES, instance=profile) if form.is_valid(): profile.save() return HttpResponseRedirect('/user/' + request.user.username) else: form = EditProfileInfoForm(instance=profile) variables = RequestContext(request, { 'media_url' : GetDefaultImageUrl(request.user), 'form' : form, }) return render_to_response('profile/profile_edit.html', variables) @login_required def upload_photo(request, user_name): if request.method == 'POST': form = UploadProfilePhotoForm(request.POST, request.FILES) if form.is_valid(): new_profile_image = form.save(commit=False) new_profile_image.name = user_name new_profile_image.isPrimary = True new_profile_image.user = request.user new_profile_image.save() return HttpResponseRedirect('/user/' + user_name) else: form = UploadProfilePhotoForm() variables = RequestContext(request, { 'media_url' : GetDefaultImageUrl(GetUser(user_name)), }) return render_to_response('profile/profilepic.html', {'form': form}, context_instance=variables) @login_required def change_photo(request, user_name, profileimg_id): try: user = User.objects.get(username=user_name) except User.DoesNotExist: raise Http404('Requested user not found.') img = user.profileimage_set.get(pk=profileimg_id) img.modified_date = datetime.now() img.save() variables = RequestContext(request, { 'user_public' : user, 'media_url' : GetDefaultImageUrl(user), }) return HttpResponseRedirect('/user/' + user_name) @login_required def delete_photo(request, user_name, profileimg_id): try: user = User.objects.get(username=user_name) except User.DoesNotExist: raise Http404('Requested user not found.') user.profileimage_set.get(pk=profileimg_id).delete() variables = RequestContext(request, { 'user_public' : user, 'media_url' : GetDefaultImageUrl(user), }) return HttpResponseRedirect('/user/' + user_name + '/profilepic')
Python
# Django settings for kokoomi project. import os SITE_ROOT = os.path.abspath(os.path.dirname(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS SERIALIZATION_MODULES = { 'json': 'serializers.json' # the wadofstuff django full serializers } DATABASES = { 'default': { 'ENGINE': 'postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'kokoomi_db', # Or path to database file if using sqlite3. 'USER': 'django', # Not used with sqlite3. 'PASSWORD': 'password', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = os.path.join(SITE_ROOT, 'site_media') # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '/site_media/' LOGIN_URL = '/login/' LOGIN_REDIRECT_URL = '/' # consider making this the user's profile or account page AUTH_PROFILE_MODULE = 'profile.UserProfile' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY = '@&$gmbry6m+%^^f5(8hs2k@64i3lsxahec^%_6@z5&7z29%ywj' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'kokoomi.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(SITE_ROOT, 'templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', 'django.contrib.gis', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'accounts', 'common', 'imagekit', 'misc', 'profile', 'reviews', 'sorting', 'south', 'tagging', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.contrib.messages.context_processors.messages', 'reviews.processors.add_search_form_processor', )
Python
from django.db import models from common.models import NameSlugModel class TagManager(models.Manager): def get_by_natural_key(self, name): return self.get(name=name) class Tag(NameSlugModel): related_tags = models.ManyToManyField('self', blank=True, symmetrical=False, through='Tag_Relation') objects = TagManager() def natural_key(self): return {'name' : self.name.replace("'", " & # 8 s "), 'id' : self.pk} def rec_lookup(self, f, st): for obj in f(): st.add(obj) obj.rec_lookup(getattr(obj, f.__name__), st) def sub_types(self): return set([rel.source for rel in self.source_relation_set.all() if rel.is_a]) def super_types(self): return set([rel.target for rel in self.target_relation_set.all() if rel.is_a]) def sub_objects(self): return set([rel.target for rel in self.target_relation_set.all() if rel.has_a]) def super_objects(self): return set([rel.source for rel in self.source_relation_set.all() if rel.has_a]) def has_related_tags(self): return self.sub_types or self.super_types or self.sub_objects or self.super_objects def rec_sub_types(self): st = set([]) self.rec_lookup(self.sub_types, st) return st def rec_super_types(self): st = set([]) self.rec_lookup(self.super_types, st) return st def rec_sub_objects(self): st = set([]) self.rec_lookup(self.sub_objects, st) return st def rec_super_objects(self): st = set([]) self.rec_lookup(self.super_objects, st) return st def all_related_tags(self): return self.rec_sub_types() | self.rec_super_types() | self.rec_sub_objects() | self.rec_super_objects() def add_sub_type(self, sub_type): return Tag_Relation(source=sub_type, target=self, is_a=True) def add_super_type(self, super_type): return Tag_Relation(source=self, target=super_type, is_a=True) def add_sub_object(self, sub_object): return Tag_Relation(source=self, target=sub_object, has_a=True) def add_super_object(self, super_object): return Tag_Relation(source=super_object, target=self, has_a=True) def __unicode__(self): return self.name class Tag_Relation(models.Model): source = models.ForeignKey(Tag, related_name='target_relation_set') target = models.ForeignKey(Tag, related_name='source_relation_set') is_a = models.BooleanField(default=False); # True if source is a target has_a = models.BooleanField(default=False); # True if source has a target class Meta: unique_together = ("source", "target") def __unicode__(self): if self.is_a: return self.source.name + " is a type of " + self.target.name elif self.has_a: return self.source.name + " consists of " + self.target.name else: return "error"
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
from django.utils.encoding import force_unicode def parse_tags(tagstring): """ Parses tag input, with multiple word input being activated and delineated by commas and double quotes. Quotes take precedence, so they may contain commas. Returns a sorted list of unique tag names. Ported from Jonathan Buchanan's `django-tagging <http://django-tagging.googlecode.com/>`_ """ if not tagstring: return [] tagstring = force_unicode(tagstring) # Special case - if there are no commas or double quotes in the # input, we don't *do* a recall... I mean, we know we only need to # split on spaces. if u',' not in tagstring and u'"' not in tagstring: words = list(set(split_strip(tagstring, u' '))) words.sort() return words words = [] buffer = [] # Defer splitting of non-quoted sections until we know if there are # any unquoted commas. to_be_split = [] saw_loose_comma = False open_quote = False i = iter(tagstring) try: while True: c = i.next() if c == u'"': if buffer: to_be_split.append(u''.join(buffer)) buffer = [] # Find the matching quote open_quote = True c = i.next() while c != u'"': buffer.append(c) c = i.next() if buffer: word = u''.join(buffer).strip() if word: words.append(word) buffer = [] open_quote = False else: if not saw_loose_comma and c == u',': saw_loose_comma = True buffer.append(c) except StopIteration: # If we were parsing an open quote which was never closed treat # the buffer as unquoted. if buffer: if open_quote and u',' in buffer: saw_loose_comma = True to_be_split.append(u''.join(buffer)) if to_be_split: if saw_loose_comma: delimiter = u',' else: delimiter = u' ' for chunk in to_be_split: words.extend(split_strip(chunk, delimiter)) words = list(set(words)) words.sort() return words def split_strip(string, delimiter=u','): """ Splits ``string`` on ``delimiter``, stripping each resulting string and returning a list of non-empty strings. Ported from Jonathan Buchanan's `django-tagging <http://django-tagging.googlecode.com/>`_ """ if not string: return [] words = [w.strip() for w in string.split(delimiter)] return [w for w in words if w] def edit_string_for_tags(tags): """ Given list of ``Tag`` instances, creates a string representation of the list suitable for editing by the user, such that submitting the given string representation back without changing it will give the same list of tags. Tag names which contain commas will be double quoted. If any tag name which isn't being quoted contains whitespace, the resulting string of tag names will be comma-delimited, otherwise it will be space-delimited. Ported from Jonathan Buchanan's `django-tagging <http://django-tagging.googlecode.com/>`_ """ names = [] for tag in tags: name = tag.name if u',' in name or u' ' in name: names.append('"%s"' % name) else: names.append(name) return u', '.join(sorted(names))
Python
# Create your views here.
Python
import settings def GetGenericAvatarImgURL(): return settings.MEDIA_URL + 'images/generic.jpg' def GetGenericFoodImgURL(): return settings.MEDIA_URL + 'images/common/missingfoodpicture.jpg'
Python
from datetime import datetime from django.db import models, IntegrityError, transaction from django.contrib.gis.db import models from django.contrib.auth.models import User from django.template.defaultfilters import slugify from imagekit.models import ImageModel class NameSlugModel(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(unique=True, editable=False) class Meta: abstract = True def save(self, *args, **kwargs): """ Based on the Tag save() method in django-taggit, this method simply stores a slugified version of the name, ensuring that the unique constraint is observed """ self.slug = slug = slugify(self.name) i = 0 while True: try: savepoint = transaction.savepoint() res = super(NameSlugModel, self).save(*args, **kwargs) transaction.savepoint_commit(savepoint) return res except IntegrityError: transaction.savepoint_rollback(savepoint) i += 1 self.slug = '%s_%d' % (slug, i) class DateAwareModel(models.Model): modified_date = models.DateTimeField(auto_now=True) created_date = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class MyImageModel(ImageModel, DateAwareModel): image = models.ImageField(upload_to='images') num_views = models.PositiveIntegerField(editable=False, default=0) class IKOptions: spec_module = 'kokoomi.reviews.specs' cache_dir = 'cache' image_field = 'image' save_count_as = 'num_views' admin_thumbnail_spec = 'thumbnail' class Meta: abstract = True class UserOwnedModel(models.Model): ''' This should be inherited by models that can form a collection associated with some user. For example, reviews or photos posted by the user. ''' user = models.ForeignKey(User) class Meta: abstract = True
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
# Create your views here.
Python
from django import forms
Python
from imagekit.specs import ImageSpec from imagekit import processors # first we define our thumbnail resize processor class ResizeThumb(processors.Resize): width = 100 height = 75 crop = True # now we define a display size resize processor class ResizeDisplay(processors.Resize): width = 600 # now let's create an adjustment processor to enhance the image at small sizes class EnchanceThumb(processors.Adjustment): contrast = 1.2 sharpness = 1.1 # now we can define our thumbnail spec class Thumbnail(ImageSpec): access_as = 'thumbnail_image' pre_cache = True processors = [ResizeThumb, EnchanceThumb] # and our display spec class Display(ImageSpec): increment_count = True processors = [ResizeDisplay]
Python
from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from imagekit.models import ImageModel from tagging.models import GenericTag class Photo(ImageModel): original_image = models.ImageField(upload_to='photos') num_views = models.PositiveIntegerField(editable=False, default=0) class IKOptions: spec_module = 'lists.specs' image_field = 'original_image' save_count_as = 'num_views' class PhotoItem(Photo): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() class Item(models.Model): name = models.CharField(max_length=140) content = models.TextField() photos = generic.GenericRelation(PhotoItem) def __unicode__(self): return self.name class Place(Item): address = models.CharField(max_length=140) zip = models.CharField(max_length=50) city = models.CharField(max_length=100) state = models.CharField(max_length=100) class Restaurant(Place): pass class NumberedItem(Item): def __unicode__(self): return self.name class List(models.Model): user = models.ForeignKey(User, blank=True, null=True) title = models.CharField(max_length=140) items = models.ManyToManyField(Item, through='ListMembership') ordering = models.CommaSeparatedIntegerField(max_length=100, default="") photos = generic.GenericRelation(PhotoItem) tags = generic.GenericRelation(GenericTag) def __unicode__(self): return self.title class ListMembership(models.Model): item = models.ForeignKey(Item) list = models.ForeignKey(List) def __unicode__(self): return str(self.item) + " in " + str(self.list) class OList(List): pass
Python
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2)
Python