code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
#!/usr/bin/env python
"""
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Configuration file for the File Manager Connector for Python
"""
# INSTALLATION NOTE: You must set up your server environment accordingly to run
# python scripts. This connector requires Python 2.4 or greater.
#
# Supported operation modes:
# * WSGI (recommended): You'll need apache + mod_python + modpython_gateway
# or any web server capable of the WSGI python standard
# * Plain Old CGI: Any server capable of running standard python scripts
# (although mod_python is recommended for performance)
# This was the previous connector version operation mode
#
# If you're using Apache web server, replace the htaccess.txt to to .htaccess,
# and set the proper options and paths.
# For WSGI and mod_python, you may need to download modpython_gateway from:
# http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this
# directory.
# SECURITY: You must explicitly enable this "connector". (Set it to "True").
# WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only
# authenticated users can access this file or use some kind of session checking.
Enabled = False
# Path to user files relative to the document root.
UserFilesPath = '/userfiles/'
# Fill the following value it you prefer to specify the absolute path for the
# user files directory. Useful if you are using a virtual directory, symbolic
# link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'UserFilesPath' must point to the same directory.
# WARNING: GetRootPath may not work in virtual or mod_python configurations, and
# may not be thread safe. Use this configuration parameter instead.
UserFilesAbsolutePath = ''
# Due to security issues with Apache modules, it is recommended to leave the
# following setting enabled.
ForceSingleExtension = True
# What the user can do with this connector
ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ]
# Allowed Resource Types
ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media']
# Do not touch this 3 lines, see "Configuration settings for each Resource Type"
AllowedExtensions = {}; DeniedExtensions = {};
FileTypesPath = {}; FileTypesAbsolutePath = {};
QuickUploadPath = {}; QuickUploadAbsolutePath = {};
# Configuration settings for each Resource Type
#
# - AllowedExtensions: the possible extensions that can be allowed.
# If it is empty then any file type can be uploaded.
# - DeniedExtensions: The extensions that won't be allowed.
# If it is empty then no restrictions are done here.
#
# For a file to be uploaded it has to fulfill both the AllowedExtensions
# and DeniedExtensions (that's it: not being denied) conditions.
#
# - FileTypesPath: the virtual folder relative to the document root where
# these resources will be located.
# Attention: It must start and end with a slash: '/'
#
# - FileTypesAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'FileTypesPath' must point to the same directory.
# Attention: It must end with a slash: '/'
#
#
# - QuickUploadPath: the virtual folder relative to the document root where
# these resources will be uploaded using the Upload tab in the resources
# dialogs.
# Attention: It must start and end with a slash: '/'
#
# - QuickUploadAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'QuickUploadPath' must point to the same directory.
# Attention: It must end with a slash: '/'
AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip']
DeniedExtensions['File'] = []
FileTypesPath['File'] = UserFilesPath + 'file/'
FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or ''
QuickUploadPath['File'] = FileTypesPath['File']
QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File']
AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png']
DeniedExtensions['Image'] = []
FileTypesPath['Image'] = UserFilesPath + 'image/'
FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or ''
QuickUploadPath['Image'] = FileTypesPath['Image']
QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image']
AllowedExtensions['Flash'] = ['swf','flv']
DeniedExtensions['Flash'] = []
FileTypesPath['Flash'] = UserFilesPath + 'flash/'
FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or ''
QuickUploadPath['Flash'] = FileTypesPath['Flash']
QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash']
AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv']
DeniedExtensions['Media'] = []
FileTypesPath['Media'] = UserFilesPath + 'media/'
FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or ''
QuickUploadPath['Media'] = FileTypesPath['Media']
QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media']
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Base Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import cgi, os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
import config as Config
class FCKeditorConnectorBase( object ):
"The base connector class. Subclass it to extend functionality (see Zope example)"
def __init__(self, environ=None):
"Constructor: Here you should parse request fields, initialize variables, etc."
self.request = FCKeditorRequest(environ) # Parse request
self.headers = [] # Clean Headers
if environ:
self.environ = environ
else:
self.environ = os.environ
# local functions
def setHeader(self, key, value):
self.headers.append ((key, value))
return
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, environ):
if environ: # WSGI
self.request = cgi.FieldStorage(fp=environ['wsgi.input'],
environ=environ,
keep_blank_values=1)
self.environ = environ
else: # plain old cgi
self.environ = os.environ
self.request = cgi.FieldStorage()
if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ:
if self.environ['REQUEST_METHOD'].upper()=='POST':
# we are in a POST, but GET query_string exists
# cgi parses by default POST data, so parse GET QUERY_STRING too
self.get_request = cgi.FieldStorage(fp=None,
environ={
'REQUEST_METHOD':'GET',
'QUERY_STRING':self.environ['QUERY_STRING'],
},
)
else:
self.get_request={}
def has_key(self, key):
return self.request.has_key(key) or self.get_request.has_key(key)
def get(self, key, default=None):
if key in self.request.keys():
field = self.request[key]
elif key in self.get_request.keys():
field = self.get_request[key]
else:
return default
if hasattr(field,"filename") and field.filename: #file upload, do not convert return value
return field
else:
return field.value
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorConnector( FCKeditorConnectorBase,
GetFoldersCommandMixin,
GetFoldersAndFilesCommandMixin,
CreateFolderCommandMixin,
UploadFileCommandMixin,
BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ):
"The Standard connector class."
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
s = ""
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.")
# Make sure we have valid inputs
for key in ("Command","Type","CurrentFolder"):
if not self.request.has_key (key):
return
# Get command, resource type and current folder
command = self.request.get("Command")
resourceType = self.request.get("Type")
currentFolder = getCurrentFolder(self.request.get("CurrentFolder"))
# Check for invalid paths
if currentFolder is None:
return self.sendError(102, "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendError( 1, 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendError( 1, 'Invalid type specified' )
# Setup paths
if command == "QuickUpload":
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
else:
self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType]
self.webUserFilesFolder = Config.FileTypesPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
if (command == "FileUpload"):
return self.uploadFile(resourceType, currentFolder)
# Create Url
url = combinePaths( self.webUserFilesFolder, currentFolder )
# Begin XML
s += self.createXmlHeader(command, resourceType, currentFolder, url)
# Execute the command
selector = {"GetFolders": self.getFolders,
"GetFoldersAndFiles": self.getFoldersAndFiles,
"CreateFolder": self.createFolder,
}
s += selector[command](resourceType, currentFolder)
s += self.createXmlFooter()
return s
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorConnector()
data = conn.doResponse()
for header in conn.headers:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Utility functions for the File Manager Connector for Python
"""
import string, re
import os
import config as Config
# Generic manipulation functions
def removeExtension(fileName):
index = fileName.rindex(".")
newFileName = fileName[0:index]
return newFileName
def getExtension(fileName):
index = fileName.rindex(".") + 1
fileExtension = fileName[index:]
return fileExtension
def removeFromStart(string, char):
return string.lstrip(char)
def removeFromEnd(string, char):
return string.rstrip(char)
# Path functions
def combinePaths( basePath, folder ):
return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' )
def getFileName(filename):
" Purpose: helper function to extrapolate the filename "
for splitChar in ["/", "\\"]:
array = filename.split(splitChar)
if (len(array) > 1):
filename = array[-1]
return filename
def sanitizeFolderName( newFolderName ):
"Do a cleanup of the folder name to avoid possible problems"
# Remove . \ / | : ? *
return re.sub( '\\.|\\\\|\\/|\\||\\:|\\?|\\*', '_', newFolderName )
def sanitizeFileName( newFileName ):
"Do a cleanup of the file name to avoid possible problems"
# Replace dots in the name with underscores (only one dot can be there... security issue).
if ( Config.ForceSingleExtension ): # remove dots
newFileName = re.sub ( '/\\.(?![^.]*$)/', '_', newFileName ) ;
newFileName = newFileName.replace('\\','/') # convert windows to unix path
newFileName = os.path.basename (newFileName) # strip directories
# Remove \ / | : ? *
return re.sub ( '/\\\\|\\/|\\||\\:|\\?|\\*/', '_', newFileName )
def getCurrentFolder(currentFolder):
if not currentFolder:
currentFolder = '/'
# Check the current folder syntax (must begin and end with a slash).
if (currentFolder[-1] <> "/"):
currentFolder += "/"
if (currentFolder[0] <> "/"):
currentFolder = "/" + currentFolder
# Ensure the folder path has no double-slashes
while '//' in currentFolder:
currentFolder = currentFolder.replace('//','/')
# Check for invalid folder paths (..)
if '..' in currentFolder:
return None
return currentFolder
def mapServerPath( environ, url):
" Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to "
# This isn't correct but for the moment there's no other solution
# If this script is under a virtual directory or symlink it will detect the problem and stop
return combinePaths( getRootPath(environ), url )
def mapServerFolder(resourceTypePath, folderPath):
return combinePaths ( resourceTypePath , folderPath )
def getRootPath(environ):
"Purpose: returns the root path on the server"
# WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python
# Use Config.UserFilesAbsolutePath instead
if environ.has_key('DOCUMENT_ROOT'):
return environ['DOCUMENT_ROOT']
else:
realPath = os.path.realpath( './' )
selfPath = environ['SCRIPT_FILENAME']
selfPath = selfPath [ : selfPath.rfind( '/' ) ]
selfPath = selfPath.replace( '/', os.path.sep)
position = realPath.find(selfPath)
# This can check only that this script isn't run from a virtual dir
# But it avoids the problems that arise if it isn't checked
raise realPath
if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''):
raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".')
return realPath[ : position ]
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
from time import gmtime, strftime
import string
def escape(text, replace=string.replace):
"""
Converts the special characters '<', '>', and '&'.
RFC 1866 specifies that these characters be represented
in HTML as < > and & respectively. In Python
1.5 we use the new string.replace() function for speed.
"""
text = replace(text, '&', '&') # must be done 1st
text = replace(text, '<', '<')
text = replace(text, '>', '>')
text = replace(text, '"', '"')
return text
def convertToXmlAttribute(value):
if (value is None):
value = ""
return escape(value)
class BaseHttpMixin(object):
def setHttpHeaders(self, content_type='text/xml'):
"Purpose: to prepare the headers for the xml to return"
# Prevent the browser from caching the result.
# Date in the past
self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT')
# always modified
self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime()))
# HTTP/1.1
self.setHeader('Cache-Control','no-store, no-cache, must-revalidate')
self.setHeader('Cache-Control','post-check=0, pre-check=0')
# HTTP/1.0
self.setHeader('Pragma','no-cache')
# Set the response format.
self.setHeader( 'Content-Type', content_type + '; charset=utf-8' )
return
class BaseXmlMixin(object):
def createXmlHeader(self, command, resourceType, currentFolder, url):
"Purpose: returns the xml header"
self.setHttpHeaders()
# Create the XML document header
s = """<?xml version="1.0" encoding="utf-8" ?>"""
# Create the main connector node
s += """<Connector command="%s" resourceType="%s">""" % (
command,
resourceType
)
# Add the current folder node
s += """<CurrentFolder path="%s" url="%s" />""" % (
convertToXmlAttribute(currentFolder),
convertToXmlAttribute(url),
)
return s
def createXmlFooter(self):
"Purpose: returns the xml footer"
return """</Connector>"""
def sendError(self, number, text):
"Purpose: in the event of an error, return an xml based error"
self.setHttpHeaders()
return ("""<?xml version="1.0" encoding="utf-8" ?>""" +
"""<Connector>""" +
self.sendErrorNode (number, text) +
"""</Connector>""" )
def sendErrorNode(self, number, text):
return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text))
class BaseHtmlMixin(object):
def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ):
self.setHttpHeaders("text/html")
"This is the function that sends the results of the uploading process"
return """<script type="text/javascript">
window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s");
</script>""" % {
'errorNumber': errorNo,
'fileUrl': fileUrl.replace ('"', '\\"'),
'fileName': fileName.replace ( '"', '\\"' ) ,
'customMsg': customMsg.replace ( '"', '\\"' ),
} | Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector/QuickUpload for Python (WSGI wrapper).
See config.py for configuration settings
"""
from connector import FCKeditorConnector
from upload import FCKeditorQuickUpload
import cgitb
from cStringIO import StringIO
# Running from WSGI capable server (recomended)
def App(environ, start_response):
"WSGI entry point. Run the connector"
if environ['SCRIPT_NAME'].endswith("connector.py"):
conn = FCKeditorConnector(environ)
elif environ['SCRIPT_NAME'].endswith("upload.py"):
conn = FCKeditorQuickUpload(environ)
else:
start_response ("200 Ok", [('Content-Type','text/html')])
yield "Unknown page requested: "
yield environ['SCRIPT_NAME']
return
try:
# run the connector
data = conn.doResponse()
# Start WSGI response:
start_response ("200 Ok", conn.headers)
# Send response text
yield data
except:
start_response("500 Internal Server Error",[("Content-type","text/html")])
file = StringIO()
cgitb.Hook(file = file).handle()
yield file.getvalue()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This is the "File Uploader" for Python
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorQuickUpload( FCKeditorConnectorBase,
UploadFileCommandMixin,
BaseHttpMixin, BaseHtmlMixin):
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"")
command = 'QuickUpload'
# The file type (from the QueryString, by default 'File').
resourceType = self.request.get('Type','File')
currentFolder = getCurrentFolder(self.request.get("CurrentFolder",""))
# Check for invalid paths
if currentFolder is None:
return self.sendUploadResults(102, '', '', "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendUploadResults( 1, '', '', 'Invalid type specified' )
# Setup paths
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
return self.uploadFile(resourceType, currentFolder)
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorQuickUpload()
data = conn.doResponse()
for header in conn.headers:
if not header is None:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python and Zope.
This code was not tested at all.
It just was ported from pre 2.5 release, so for further reference see
\editor\filemanager\browser\default\connectors\py\connector.py in previous
releases.
"""
from fckutil import *
from connector import *
import config as Config
class FCKeditorConnectorZope(FCKeditorConnector):
"""
Zope versiof FCKeditorConnector
"""
# Allow access (Zope)
__allow_access_to_unprotected_subobjects__ = 1
def __init__(self, context=None):
"""
Constructor
"""
FCKeditorConnector.__init__(self, environ=None) # call superclass constructor
# Instance Attributes
self.context = context
self.request = FCKeditorRequest(context)
def getZopeRootContext(self):
if self.zopeRootContext is None:
self.zopeRootContext = self.context.getPhysicalRoot()
return self.zopeRootContext
def getZopeUploadContext(self):
if self.zopeUploadContext is None:
folderNames = self.userFilesFolder.split("/")
c = self.getZopeRootContext()
for folderName in folderNames:
if (folderName <> ""):
c = c[folderName]
self.zopeUploadContext = c
return self.zopeUploadContext
def setHeader(self, key, value):
self.context.REQUEST.RESPONSE.setHeader(key, value)
def getFolders(self, resourceType, currentFolder):
# Open the folders node
s = ""
s += """<Folders>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["Folder"]):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(name)
)
# Close the folders node
s += """</Folders>"""
return s
def getZopeFoldersAndFiles(self, resourceType, currentFolder):
folders = self.getZopeFolders(resourceType, currentFolder)
files = self.getZopeFiles(resourceType, currentFolder)
s = folders + files
return s
def getZopeFiles(self, resourceType, currentFolder):
# Open the files node
s = ""
s += """<Files>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["File","Image"]):
s += """<File name="%s" size="%s" />""" % (
convertToXmlAttribute(name),
((o.get_size() / 1024) + 1)
)
# Close the files node
s += """</Files>"""
return s
def findZopeFolder(self, resourceType, folderName):
# returns the context of the resource / folder
zopeFolder = self.getZopeUploadContext()
folderName = self.removeFromStart(folderName, "/")
folderName = self.removeFromEnd(folderName, "/")
if (resourceType <> ""):
try:
zopeFolder = zopeFolder[resourceType]
except:
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType)
zopeFolder = zopeFolder[resourceType]
if (folderName <> ""):
folderNames = folderName.split("/")
for folderName in folderNames:
zopeFolder = zopeFolder[folderName]
return zopeFolder
def createFolder(self, resourceType, currentFolder):
# Find out where we are
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
errorNo = 0
errorMsg = ""
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder)
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def uploadFile(self, resourceType, currentFolder, count=None):
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
file = self.request.get("NewFile", None)
fileName = self.getFileName(file.filename)
fileNameOnly = self.removeExtension(fileName)
fileExtension = self.getExtension(fileName).lower()
if (count):
nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension)
else:
nid = fileName
title = nid
try:
zopeFolder.manage_addProduct['OFSP'].manage_addFile(
id=nid,
title=title,
file=file.read()
)
except:
if (count):
count += 1
else:
count = 1
return self.zopeFileUpload(resourceType, currentFolder, count)
return self.sendUploadResults( 0 )
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, context=None):
r = context.REQUEST
self.request = r
def has_key(self, key):
return self.request.has_key(key)
def get(self, key, default=None):
return self.request.get(key, default)
"""
Running from zope, you will need to modify this connector.
If you have uploaded the FCKeditor into Zope (like me), you need to
move this connector out of Zope, and replace the "connector" with an
alias as below. The key to it is to pass the Zope context in, as
we then have a like to the Zope context.
## Script (Python) "connector.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=*args, **kws
##title=ALIAS
##
import Products.zope as connector
return connector.FCKeditorConnectorZope(context=context).doResponse()
"""
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Sample page.
"""
import cgi
import os
# Ensure that the fckeditor.py is included in your classpath
import fckeditor
# Tell the browser to render html
print "Content-Type: text/html"
print ""
# Document header
print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>FCKeditor - Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">
<link href="../sample.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>FCKeditor - Python - Sample 1</h1>
This sample displays a normal HTML form with an FCKeditor with full features
enabled.
<hr>
<form action="sampleposteddata.py" method="post" target="_blank">
"""
# This is the real work
try:
sBasePath = os.environ.get("SCRIPT_NAME")
sBasePath = sBasePath[0:sBasePath.find("_samples")]
oFCKeditor = fckeditor.FCKeditor('FCKeditor1')
oFCKeditor.BasePath = sBasePath
oFCKeditor.Value = """<p>This is some <strong>sample text</strong>. You are using <a href="http://www.fckeditor.net/">FCKeditor</a>.</p>"""
print oFCKeditor.Create()
except Exception, e:
print e
print """
<br>
<input type="submit" value="Submit">
</form>
"""
# For testing your environments
print "<hr>"
for key in os.environ.keys():
print "%s: %s<br>" % (key, os.environ.get(key, ""))
print "<hr>"
# Document footer
print """
</body>
</html>
"""
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This page lists the data posted by a form.
"""
import cgi
import os
# Tell the browser to render html
print "Content-Type: text/html"
print ""
try:
# Create a cgi object
form = cgi.FieldStorage()
except Exception, e:
print e
# Document header
print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>FCKeditor - Samples - Posted Data</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">
<link href="../sample.css" rel="stylesheet" type="text/css" />
</head>
<body>
"""
# This is the real work
print """
<h1>FCKeditor - Samples - Posted Data</h1>
This page lists all data posted by the form.
<hr>
<table width="100%" border="1" cellspacing="0" bordercolor="#999999">
<tr style="FONT-WEIGHT: bold; COLOR: #dddddd; BACKGROUND-COLOR: #999999">
<td nowrap>Field Name </td>
<td>Value</td>
</tr>
"""
for key in form.keys():
try:
value = form[key].value
print """
<tr>
<td valign="top" nowrap><b>%s</b></td>
<td width="100%%" style="white-space:pre">%s</td>
</tr>
""" % (key, value)
except Exception, e:
print e
print "</table>"
# For testing your environments
print "<hr>"
for key in os.environ.keys():
print "%s: %s<br>" % (key, os.environ.get(key, ""))
print "<hr>"
# Document footer
print """
</body>
</html>
"""
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Sample page.
"""
import cgi
import os
# Ensure that the fckeditor.py is included in your classpath
import fckeditor
# Tell the browser to render html
print "Content-Type: text/html"
print ""
# Document header
print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>FCKeditor - Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">
<link href="../sample.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>FCKeditor - Python - Sample 1</h1>
This sample displays a normal HTML form with an FCKeditor with full features
enabled.
<hr>
<form action="sampleposteddata.py" method="post" target="_blank">
"""
# This is the real work
try:
sBasePath = os.environ.get("SCRIPT_NAME")
sBasePath = sBasePath[0:sBasePath.find("_samples")]
oFCKeditor = fckeditor.FCKeditor('FCKeditor1')
oFCKeditor.BasePath = sBasePath
oFCKeditor.Value = """<p>This is some <strong>sample text</strong>. You are using <a href="http://www.fckeditor.net/">FCKeditor</a>.</p>"""
print oFCKeditor.Create()
except Exception, e:
print e
print """
<br>
<input type="submit" value="Submit">
</form>
"""
# For testing your environments
print "<hr>"
for key in os.environ.keys():
print "%s: %s<br>" % (key, os.environ.get(key, ""))
print "<hr>"
# Document footer
print """
</body>
</html>
"""
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This page lists the data posted by a form.
"""
import cgi
import os
# Tell the browser to render html
print "Content-Type: text/html"
print ""
try:
# Create a cgi object
form = cgi.FieldStorage()
except Exception, e:
print e
# Document header
print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>FCKeditor - Samples - Posted Data</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">
<link href="../sample.css" rel="stylesheet" type="text/css" />
</head>
<body>
"""
# This is the real work
print """
<h1>FCKeditor - Samples - Posted Data</h1>
This page lists all data posted by the form.
<hr>
<table width="100%" border="1" cellspacing="0" bordercolor="#999999">
<tr style="FONT-WEIGHT: bold; COLOR: #dddddd; BACKGROUND-COLOR: #999999">
<td nowrap>Field Name </td>
<td>Value</td>
</tr>
"""
for key in form.keys():
try:
value = form[key].value
print """
<tr>
<td valign="top" nowrap><b>%s</b></td>
<td width="100%%" style="white-space:pre">%s</td>
</tr>
""" % (key, value)
except Exception, e:
print e
print "</table>"
# For testing your environments
print "<hr>"
for key in os.environ.keys():
print "%s: %s<br>" % (key, os.environ.get(key, ""))
print "<hr>"
# Document footer
print """
</body>
</html>
"""
| Python |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import os.path
import sys
CMD_CLASS = None
try:
from googlecode_distutils_upload import upload
CMD_CLASS = {'google_upload': upload}
except Exception:
pass
import filecache
DOCUMENTATION = filecache.__doc__
VERSION = '0.75'
SETUP_DICT = dict(
name='filecache',
packages=['filecache'],
version=VERSION,
author='ubershmekel',
author_email='ubershmekel@gmail.com',
url='http://code.google.com/p/filecache/',
description='Persistent caching decorator',
long_description=DOCUMENTATION,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Utilities',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
if CMD_CLASS:
SETUP_DICT['cmdclass'] = CMD_CLASS
# generate .rst file with documentation
#open(os.path.join(os.path.dirname(__file__), 'documentation.rst'), 'w').write(DOCUMENTATION)
setup(**SETUP_DICT)
| Python |
import time
from filecache import filecache
@filecache(30)
def the_time():
return time.time()
| Python |
'''
filecache
filecache is a decorator which saves the return value of functions even
after the interpreter dies. For example this is useful on functions that download
and parse webpages. All you need to do is specify how long
the return values should be cached (use seconds, like time.sleep).
USAGE:
from filecache import filecache
@filecache(24 * 60 * 60)
def time_consuming_function(args):
# etc
@filecache(filecache.YEAR)
def another_function(args):
# etc
NOTE: All arguments of the decorated function and the return value need to be
picklable for this to work.
NOTE: The cache isn't automatically cleaned, it is only overwritten. If your
function can receive many different arguments that rarely repeat, your
cache may forever grow. One day I might add a feature that once in every
100 calls scans the db for outdated stuff and erases.
NOTE: This is less useful on methods of a class because the instance (self)
is cached, and if the instance isn't the same, the cache isn't used. This
makes sense because class methods are affected by changes in whatever
is attached to self.
Tested on python 2.7 and 3.1
License: BSD, do what you wish with this. Could be awesome to hear if you found
it useful and/or you have suggestions. ubershmekel at gmail
A trick to invalidate a single value:
@filecache.filecache
def somefunc(x, y, z):
return x * y * z
del somefunc._db[filecache._args_key(somefunc, (1,2,3), {})]
# or just iterate of somefunc._db (it's a shelve, like a dict) to find the right key.
'''
import collections as _collections
import datetime as _datetime
import functools as _functools
import inspect as _inspect
import os as _os
import pickle as _pickle
import shelve as _shelve
import sys as _sys
import time as _time
import traceback as _traceback
import types
_retval = _collections.namedtuple('_retval', 'timesig data')
_SRC_DIR = _os.path.dirname(_os.path.abspath(__file__))
SECOND = 1
MINUTE = 60 * SECOND
HOUR = 60 * MINUTE
DAY = 24 * HOUR
WEEK = 7 * DAY
MONTH = 30 * DAY
YEAR = 365 * DAY
FOREVER = None
OPEN_DBS = dict()
def _get_cache_name(function):
"""
returns a name for the module's cache db.
"""
module_name = _inspect.getfile(function)
cache_name = module_name
# fix for '<string>' or '<stdin>' in exec or interpreter usage.
cache_name = cache_name.replace('<', '_lt_')
cache_name = cache_name.replace('>', '_gt_')
cache_name += '.cache'
return cache_name
def _log_error(error_str):
try:
error_log_fname = _os.path.join(_SRC_DIR, 'filecache.err.log')
if _os.path.isfile(error_log_fname):
fhand = open(error_log_fname, 'a')
else:
fhand = open(error_log_fname, 'w')
fhand.write('[%s] %s\r\n' % (_datetime.datetime.now().isoformat(), error_str))
fhand.close()
except Exception:
pass
def _args_key(function, args, kwargs):
arguments = (args, kwargs)
# Check if you have a valid, cached answer, and return it.
# Sadly this is python version dependant
if _sys.version_info[0] == 2:
arguments_pickle = _pickle.dumps(arguments)
else:
# NOTE: protocol=0 so it's ascii, this is crucial for py3k
# because shelve only works with proper strings.
# Otherwise, we'd get an exception because
# function.__name__ is str but dumps returns bytes.
arguments_pickle = _pickle.dumps(arguments, protocol=0).decode('ascii')
key = function.__name__ + arguments_pickle
return key
def filecache(seconds_of_validity=None, fail_silently=False):
'''
filecache is called and the decorator should be returned.
'''
def filecache_decorator(function):
@_functools.wraps(function)
def function_with_cache(*args, **kwargs):
try:
key = _args_key(function, args, kwargs)
if key in function._db:
rv = function._db[key]
if seconds_of_validity is None or _time.time() - rv.timesig < seconds_of_validity:
return rv.data
except Exception:
# in any case of failure, don't let filecache break the program
error_str = _traceback.format_exc()
_log_error(error_str)
if not fail_silently:
raise
retval = function(*args, **kwargs)
# store in cache
# NOTE: no need to _db.sync() because there was no mutation
# NOTE: it's importatnt to do _db.sync() because otherwise the cache doesn't survive Ctrl-Break!
try:
function._db[key] = _retval(_time.time(), retval)
function._db.sync()
except Exception:
# in any case of failure, don't let filecache break the program
error_str = _traceback.format_exc()
_log_error(error_str)
if not fail_silently:
raise
return retval
# make sure cache is loaded
if not hasattr(function, '_db'):
cache_name = _get_cache_name(function)
if cache_name in OPEN_DBS:
function._db = OPEN_DBS[cache_name]
else:
function._db = _shelve.open(cache_name)
OPEN_DBS[cache_name] = function._db
function_with_cache._db = function._db
return function_with_cache
if type(seconds_of_validity) == types.FunctionType:
# support for when people use '@filecache.filecache' instead of '@filecache.filecache()'
func = seconds_of_validity
return filecache_decorator(func)
return filecache_decorator
| Python |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fileprocess.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| Python |
#coding=utf-8
from django.conf.urls 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'^$', 'fileprocess.views.home', name='home'),
# url(r'^fileprocess/', include('fileprocess.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)),
#process app
url(r'^fileprocess/',include('fileprocess.process.urls')),
)
| Python |
# Django settings for fileprocess project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', '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.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.4/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# 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.
# In a Windows environment this must be set to your system time zone.
#TIME_ZONE = 'America/Chicago'
TIME_ZONE = 'Asia/Shanghai'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
#LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'zh-cn'
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
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = 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/'
# 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 = 'km*@znc72f9-#br*)u7cw9e56kr=+s^mwtwqt%8$%f0w^w$l@f'
# 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',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'fileprocess.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'fileprocess.wsgi.application'
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 when DEBUG=False.
# 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,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
| Python |
from django.db import models
# Create your models here.
| 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 |
#coding=utf-8
from django.conf.urls import patterns, url
import views
urlpatterns = patterns(
url(r'^$', views.index, name='index'),
url(r'filetopic$', views.filetopic, name='filetopic'),
url(r'getpic$', views.getPic, name='getpic')
)
| Python |
#coding=utf-8
# Create your views here.
import json
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from filepic import GeneratePic
def index(request):
return HttpResponse("Hello, world. You're at the poll index.")
@csrf_exempt
def filetopic(request):
"""请求处理"""
#读取请求
print request.method
if request.method == 'POST':
jsonData=request.raw_post_data
print jsonData
jsonData=json.loads(jsonData)
requestId=jsonData["requestId"]
requestId=str(requestId)
fieldsData=jsonData["fields"]
cls=GeneratePic()
resultJson=cls.enter(fieldsData)
resultJson["responseId"]=requestId
#转换成JSON,解决中文问题
resultJson=json.dumps(resultJson,encoding="UTF-8",ensure_ascii=False)
return HttpResponse(resultJson)
return HttpResponse("Hello, world. You're at the pic index,Please use post method")
@csrf_exempt
def getPic(request):
"""Get Pic File"""
if request.method=='POST':
jsonData=request.raw_post_data
print jsonData
jsonData=json.loads(jsonData)
requestId=jsonData["requestId"]
requestId=str(requestId)
fieldsData=jsonData["fields"]
picPath=fieldsData["picPath"]
if picPath!="":
try:
def readFile(fn, buf_size=262144):
f = open(fn, "rb")
while True:
c = f.read(buf_size)
if c:
yield c
else:
break
f.close()
response = HttpResponse(readFile(picPath), mimetype='application/octet-stream')
response['Content-Disposition'] = 'attachment; filename=%s' %picPath
return response
except Exception, e:
print e
return HttpResponse("Hello, world. You're at the getPic ,Please use post method")
| Python |
#coding=utf-8
import commands
import os
import uuid
class GeneratePic():
"""
文件生成图片列表
"""
def enter(self, fieldsData):
"""
处理程序入口,根据附件的类型,调用不同的方法
"""
resultJson={}
imageJsonArray=[]
errorMsg=""
picPath=fieldsData["picPath"]
filePath=fieldsData["filePath"]
if picPath=="":
picPath="/tmp/"+str(uuid.uuid1()).replace("-", "")+"/"
print "picPath="+picPath
d = os.path.dirname(picPath)
print(d)
if not os.path.exists(d):
print "mkdir "+picPath
os.makedirs(d)
fileType=filePath[filePath.rfind(".")+1:]
fileType=fileType.lower()
if fileType=="doc" or fileType=="docx" or fileType=="xls" or fileType=="xlst":
print "文件类型为DOC文件"
pdfFilePath=self.docToPdf(picPath, filePath)
imageJsonArray,errorMsg=self.pdfToPic(pdfFilePath,picPath,imageJsonArray,errorMsg)
elif fileType=='pdf':
imageJsonArray,errorMsg=self.pdfToPic(filePath,picPath,imageJsonArray,errorMsg)
else:
errorMsg="文件类型不支持"
print errorMsg
#sort
if imageJsonArray.__len__()>1:
print "对imageJsonArray进行排序"
imageJsonArray=sorted(imageJsonArray, key=lambda x:int(x[x.rfind("/")+9:-4]))
resultJson["imageList"]=imageJsonArray
resultJson["errorMsg"]=errorMsg
print resultJson
return resultJson
def docToPdf(self,picPath, file):
"""
convert doc to pdf
"""
if not (file is None):
print "开始转换文件"
try:
pdfFileDir=file
pdfFileDir=pdfFileDir.replace("\\", "/")
pdfFileDir=pdfFileDir[0:pdfFileDir.rfind("/")]
print "pdfFileDir="+pdfFileDir
docFileName=file[file.rfind("/"):]
print "docFileName="+docFileName
pdfFileName=docFileName.replace(".docx", "")
pdfFileName=pdfFileName.replace(".doc", "")
pdfFileName=pdfFileName.replace(".xlsx", "")
pdfFileName=pdfFileName.replace(".xls", "")
pdfFileName=pdfFileName+".pdf"
status, output = commands.getstatusoutput("libreoffice --headless --convert-to pdf %s --outdir %s" %(file, pdfFileDir))
if status==0:
print output
pdfFilePath=pdfFileDir+pdfFileName
print "pdfFilePath="+pdfFilePath
print "convert doc to pdf success"
return pdfFilePath
else:
print output
except Exception, e:
print e
print "转换文件结束"
return ""
def pdfToPic(self,pdfFilePath,picPath,imageJsonArray,errorMsg):
"""PDF转换PIC"""
if pdfFilePath!="":
try:
print "convert image to dir %s"%pdfFilePath
pdfFilePath=pdfFilePath.encode('utf-8')
exeCmd="convert %s %s/convert.png" %(pdfFilePath, picPath)
print "start execute cmd "+exeCmd
status, output = commands.getstatusoutput(exeCmd)
if status==0:
print "执行Convert命令结束"
for imageFile in os.listdir(picPath):
tempPicPath=picPath+"/"+imageFile
print "图片文件是"+tempPicPath
imageJsonArray.append(tempPicPath)
except Exception, e:
print e
errorMsg="文件转换失败"
return imageJsonArray,errorMsg | Python |
#coding=utf-8
"""
WSGI config for fileprocess project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fileprocess.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
| Python |
"""Downloads files from http or ftp locations.
Copyright Joshua Banton"""
import os
import urllib2
import ftplib
import urlparse
import urllib
import sys
import socket
version = "0.4.0"
class DownloadFile(object):
"""This class is used for downloading files from the internet via http or ftp.
It supports basic http authentication and ftp accounts, and supports resuming downloads.
It does not support https or sftp at this time.
The main advantage of this class is it's ease of use, and pure pythoness. It only uses the Python standard library,
so no dependencies to deal with, and no C to compile.
#####
If a non-standard port is needed just include it in the url (http://example.com:7632).
Basic usage:
Simple
downloader = fileDownloader.DownloadFile('http://example.com/file.zip')
downloader.download()
Use full path to download
downloader = fileDownloader.DownloadFile('http://example.com/file.zip', "C:/Users/username/Downloads/newfilename.zip")
downloader.download()
Basic Authentication protected download
downloader = fileDownloader.DownloadFile('http://example.com/file.zip', "C:/Users/username/Downloads/newfilename.zip", ('username','password'))
downloader.download()
Resume
downloader = fileDownloader.DownloadFile('http://example.com/file.zip')
downloader.resume()
"""
def __init__(self, url, localFileName=None, auth=None, timeout=120.0, autoretry=False, retries=5):
"""Note that auth argument expects a tuple, ('username','password')"""
self.url = url
self.urlFileName = None
self.progress = 0
self.fileSize = None
self.localFileName = localFileName
self.type = self.getType()
self.auth = auth
self.timeout = timeout
self.retries = retries
self.curretry = 0
self.cur = 0
try:
self.urlFilesize = self.getUrlFileSize()
except urllib2.HTTPError:
self.urlFilesize = None
if not self.localFileName: #if no filename given pulls filename from the url
self.localFileName = self.getUrlFilename(self.url)
def __downloadFile__(self, urlObj, fileObj, callBack=None):
"""starts the download loop"""
self.fileSize = self.getUrlFileSize()
while 1:
try:
data = urlObj.read(8192)
except (socket.timeout, socket.error) as t:
print "caught ", t
self.__retry__()
break
if not data:
fileObj.close()
break
fileObj.write(data)
self.cur += 8192
if callBack:
callBack(cursize=self.cur)
def __retry__(self):
"""auto-resumes up to self.retries"""
if self.retries > self.curretry:
self.curretry += 1
if self.getLocalFileSize() != self.urlFilesize:
self.resume()
else:
print 'retries all used up'
return False, "Retries Exhausted"
def __authHttp__(self):
"""handles http basic authentication"""
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
# this creates a password manager
passman.add_password(None, self.url, self.auth[0], self.auth[1])
# because we have put None at the start it will always
# use this username/password combination for urls
authhandler = urllib2.HTTPBasicAuthHandler(passman)
# create the AuthHandler
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
def __authFtp__(self):
"""handles ftp authentication"""
ftped = urllib2.FTPHandler()
ftpUrl = self.url.replace('ftp://', '')
req = urllib2.Request("ftp://%s:%s@%s"%(self.auth[0], self.auth[1], ftpUrl))
req.timeout = self.timeout
ftpObj = ftped.ftp_open(req)
return ftpObj
def __startHttpResume__(self, restart=None, callBack=None):
"""starts to resume HTTP"""
curSize = self.getLocalFileSize()
if curSize >= self.urlFilesize:
return False
self.cur = curSize
if restart:
f = open(self.localFileName , "wb")
else:
f = open(self.localFileName , "ab")
if self.auth:
self.__authHttp__()
req = urllib2.Request(self.url)
req.headers['Range'] = 'bytes=%s-%s' % (curSize, self.getUrlFileSize())
urllib2Obj = urllib2.urlopen(req, timeout=self.timeout)
self.__downloadFile__(urllib2Obj, f, callBack=callBack)
def __startFtpResume__(self, restart=None):
"""starts to resume FTP"""
curSize = self.getLocalFileSize()
if curSize >= self.urlFilesize:
return False
if restart:
f = open(self.localFileName , "wb")
else:
f = open(self.localFileName , "ab")
ftper = ftplib.FTP(timeout=60)
parseObj = urlparse.urlparse(self.url)
baseUrl= parseObj.hostname
urlPort = parseObj.port
bPath = os.path.basename(parseObj.path)
gPath = parseObj.path.replace(bPath, "")
unEncgPath = urllib.unquote(gPath)
fileName = urllib.unquote(os.path.basename(self.url))
ftper.connect(baseUrl, urlPort)
ftper.login(self.auth[0], self.auth[1])
if len(gPath) > 1:
ftper.cwd(unEncgPath)
ftper.sendcmd("TYPE I")
ftper.sendcmd("REST " + str(curSize))
downCmd = "RETR "+ fileName
ftper.retrbinary(downCmd, f.write)
def getUrlFilename(self, url):
"""returns filename from url"""
return urllib.unquote(os.path.basename(url))
def getUrlFileSize(self):
"""gets filesize of remote file from ftp or http server"""
if self.type == 'http':
if self.auth:
authObj = self.__authHttp__()
urllib2Obj = urllib2.urlopen(self.url, timeout=self.timeout)
size = urllib2Obj.headers.get('content-length')
return size
def getLocalFileSize(self):
"""gets filesize of local file"""
size = os.stat(self.localFileName).st_size
return size
def getType(self):
"""returns protocol of url (ftp or http)"""
type = urlparse.urlparse(self.url).scheme
return type
def checkExists(self):
"""Checks to see if the file in the url in self.url exists"""
if self.auth:
if self.type == 'http':
authObj = self.__authHttp__()
try:
urllib2.urlopen(self.url, timeout=self.timeout)
except urllib2.HTTPError:
return False
return True
elif self.type == 'ftp':
return "not yet supported"
else:
urllib2Obj = urllib2.urlopen(self.url, timeout=self.timeout)
try:
urllib2.urlopen(self.url, timeout=self.timeout)
except urllib2.HTTPError:
return False
return True
def download(self, callBack=None):
"""starts the file download"""
self.curretry = 0
self.cur = 0
f = open(self.localFileName , "wb")
if self.auth:
if self.type == 'http':
self.__authHttp__()
urllib2Obj = urllib2.urlopen(self.url, timeout=self.timeout)
self.__downloadFile__(urllib2Obj, f, callBack=callBack)
elif self.type == 'ftp':
self.url = self.url.replace('ftp://', '')
authObj = self.__authFtp__()
self.__downloadFile__(authObj, f, callBack=callBack)
else:
urllib2Obj = urllib2.urlopen(self.url, timeout=self.timeout)
self.__downloadFile__(urllib2Obj, f, callBack=callBack)
return True
def resume(self, callBack=None):
"""attempts to resume file download"""
type = self.getType()
if type == 'http':
self.__startHttpResume__(callBack=callBack)
elif type == 'ftp':
self.__startFtpResume__()
| Python |
import fileDownloader
class DownloadFile(fileDownloader.DownloadFile):
pass | Python |
from setuptools import setup, find_packages
setup(name='fileDownloader.py',
version='0.4.0',
description="Downloads files via HTTP or FTP",
download_url="http://code.google.com/p/filedownload/downloads/list",
packages = find_packages(exclude="test"),
long_description="""Intro
This module is used for downloading files from the internet via http or ftp.
It supports basic http authentication and ftp accounts, and supports resuming downloads. It does not support https or sftp at this time. The main advantage of this package is it's ease of use, and pure pythoness. It only uses the Python standard library, so no dependencies to deal with, and no C to compile.
Usage
If a non-standard port is needed just include it in the url (http://example.com:7632).
Simple
downloader = fileDownloader.DownloadFile('http://example.com/file.zip')
downloader.download()
Use full path to download
downloader = fileDownloader.DownloadFile('http://example.com/file.zip', "C:\\Users\\username\\Downloads\\newfilename.zip")
downloader.download()
Password protected download
downloader = fileDownloader.DownloadFile('http://example.com/file.zip', "C:\\Users\\username\\Downloads\\newfilename.zip", ('username','password'))
downloader.download()
Resume
downloader = fileDownloader.DownloadFile('http://example.com/file.zip')
downloader.resume()""",
classifiers=[
"Programming Language :: Python",
("Topic :: Software Development :: Libraries :: Python Modules"),
],
keywords='download',
author='Joshua Banton',
author_email='bantonj@gmail.com',
url='http://bantonj.wordpress.com/software/open-source/',
license='MIT')
| Python |
# Django settings for library project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = '' # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_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.
# 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
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# 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 = ''
# 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 = '5xqs5p$+0k96wb5=*4odik6ttn+*ipt3i^7=4=&opcvp$^t9j%'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.doc.XViewMiddleware',
)
ROOT_URLCONF = 'library.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',
)
| Python |
#!/usr/bin/env python
from django.core.management import execute_manager
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 *
urlpatterns = patterns('',
# Example:
# (r'^library/', include('library.foo.urls')),
# Uncomment this for admin:
# (r'^admin/', include('django.contrib.admin.urls')),
)
| Python |
#!/usr/bin/env python
from django.core.management import execute_manager
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 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "filex.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| Python |
# -*- coding: utf-8 -*-
from django.db import models
from django import forms
from django.utils.translation import ugettext_lazy as _
# Create your models here.
TYPE_ENT = (
( 'ROOT' , 'ROOT' ),
( 'TIERS', 'TIERS'),
)
class tstClass(models.Model):
codent = models.CharField(_(u'Code Entite'),max_length=20, unique=True)
noment = models.CharField(_(u'Nom Entite'),max_length=40)
description = models.TextField(_(u'Description'))
typent = models.CharField(_(u'Type Entite'), max_length=10, choices=TYPE_ENT, default='TIERS' )
def __unicode__(self):
return "%s : %s" % (self.codent, self.noment)
class tstForm(forms.ModelForm):
codent = forms.CharField(label='Code Entité ',max_length=20)
noment = forms.CharField(label='Nom Entité ',max_length=40)
description = forms.CharField(label='Description ', widget=forms.Textarea, required=False)
typent = forms.ChoiceField( label='Type Entité ',choices=TYPE_ENT, initial='TIERS')
class Meta:
model = tstClass
| 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 |
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from models import tstClass
from views import URLDelete
urlpatterns = patterns('tst.views',
# Examples:
# url(r'^$', 'filex.views.home', name='home'),
# url(r'^filex/', include('filex.foo.urls')),
## model : le modele de donnees
## template : le template a utiliser
## base_href : la base pour les actions de modif delete
## p : le nombre d'object par pagination
url(r'^$', 'std_liste', { 'model':tstClass, 'template':'tmpl/tst/list_tst.html', 'base_href':'/tst', 'p':10, }, name='url_liste'),
url(r'^liste/$', 'std_liste', { 'model':tstClass, 'template':'tmpl/tst/list_tst.html', 'base_href':'/tst', 'p':10, }, name='url_liste'),
## Creation
url(r'^create/$', 'tst_create', name='tst_create'),
## Modif
url(r'^modif/(\d+)$', 'tst_modif', name='tst_modif'),
## Delete
url(r'^delete/(?P<code>\d+)/$', URLDelete.as_view(), name='url_delete'),
)
| Python |
# -*- coding: utf-8 -*-
from django.contrib import admin
from tst.models import tstClass
admin.site.register(tstClass)
| Python |
# -*- coding: utf-8 -*-
# Create your views here.
from django.template import Context, loader
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, get_list_or_404
from django.shortcuts import render, render_to_response
from django.shortcuts import HttpResponseRedirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from models import tstClass
from models import tstForm
import datetime
import pdb
def get_pub_date():
d = datetime.datetime.now()
return d.strftime("%d/%m/%Y %X")
## --------------------------------
## Effacement avec ClassBase View
## --------------------------------
class URLDelete(DeleteView):
model = tstClass
context_object_name = "obj"
template_name = 'tmpl/tst/tst_delete.html'
#success_url = reverse_lazy('tst/')
success_url = '/tst/'
def get_object(self, queryset=None):
enreg_id = self.kwargs.get('code', None)
return get_object_or_404(tstClass, id=enreg_id)
## -----------------
## Modif d'un enreg
## -----------------
def tst_modif(request, enreg_id):
if request.method == 'POST':
if request.POST['VALID'] == 'VALID':
a = tstClass.objects.get(id=enreg_id)
f = tstForm(request.POST, instance=a)
if f.is_valid():
f.save()
return HttpResponseRedirect('/tst')
else:
## Bouton ANNUL
return HttpResponseRedirect('/tst')
else:
a = tstClass.objects.get(pk=enreg_id)
f = tstForm(instance=a)
return render( request, 'tmpl/tst/tst_modif.html', { 'form' : f, 'ENREG':enreg_id, 'PUB_DATE':get_pub_date() } )
## -----------------------
## Creation d'un enreg
## -----------------------
def tst_create(request):
if request.method == 'POST':
## Bouton VALID
if request.POST['VALID'] == 'VALID':
#pdb.set_trace()
f = tstForm(request.POST)
if f.is_valid():
new_cle = f.cleaned_data['codent']
try:
q = tstClass.objects.get(codent=new_cle)
except:
q = None
if q:
f.errors['__all__'] = f.error_class(["Cle Deja Existante"])
else:
new_enreg = tstClass()
new_enreg.codent = f.cleaned_data['codent']
new_enreg.noment = f.cleaned_data['noment']
new_enreg.description = f.cleaned_data['description']
new_enreg.typent = f.cleaned_data['typent']
new_enreg.save()
return HttpResponseRedirect('/tst')
else:
## Bouton ANNUL
return HttpResponseRedirect('/tst')
else:
f = tstForm()
return render( request, 'tmpl/tst/tst_create.html', { 'form' : f, 'PUB_DATE':get_pub_date() } )
## --------------------------------
## Liste Standard avec pagination
## --------------------------------
def std_liste(request, model, template, base_href, p=10):
obj_list = model.objects.all()
paginator = Paginator(obj_list, p)
page = request.GET.get('page')
try:
objs = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
objs = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
objs = paginator.page(paginator.num_pages)
return render_to_response(template, {"objs": objs, 'B_HREF':base_href, 'PUB_DATE':get_pub_date() })
| Python |
from django.db import models
| Python |
from django.conf.urls import patterns, include, url
from django.views.generic.simple import direct_to_template
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'filex.views.home', name='home'),
# url(r'^filex/', include('filex.foo.urls')),
# Home
url(r'^$', 'filex.views.index', name='home' ),
# Login
url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'tmpl/login.html'}),
# Menu
url(r'^menu$', 'filex.views.menu', name='menu' ),
# Autre fonctions
url(r'^param$', 'filex.views.param', name='param' ),
url(r'^put_file$', 'filex.views.put_file', name='put_file' ),
url(r'^get_file$', 'filex.views.get_file', name='get_file' ),
## Gestion des fichiers Ex
url(r'^fex/', include('fex.urls')),
#url(r'^fex/(?P<fex_id>\d+)/$', 'fex.views.fex_detail', name='fex_detail' ),
## TEST
url(r'^tst/', include('tst.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 filex project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('chris', 'chris@example.com'),
)
## 2 env de dev
BASE_DIR = '/home/chris/Bureau/DVP/python/file-exchange/filex'
#BASE_DIR = '/root/tmp/file-exchange/filex'
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'db/data.dbf', # 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.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/Paris'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'fr-fr'
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
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
# MEDIA_ROOT = ''
MEDIA_ROOT = BASE_DIR
# 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/'
# 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.
BASE_DIR+'/static',
)
# 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 = 's#13+rlwepsgwo%-3%)qp(0p+f_js8ys&3f-ciz8op*and4!m3'
# 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',
'debug_toolbar.middleware.DebugToolbarMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS' : False,
}
ROOT_URLCONF = 'filex.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'filex.wsgi.application'
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.
BASE_DIR
)
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',
'fex',
'tst',
'debug_toolbar',
)
# 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 when DEBUG=False.
# 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,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
| Python |
# -*- coding: utf-8 -*-
from django.template import Context, loader
from django.http import HttpResponse
import datetime
def hello(request):
return HttpResponse("Hello, world.")
def index(request):
t = loader.get_template('tmpl/index.html')
d = datetime.datetime.now()
PUB_DATE = d.strftime("%d/%m/%Y %X")
c = Context({
'DATA': "TEST DE DATA",
'PUB_DATE':PUB_DATE,
'TITRE_PAGE' : 'WELCOME',
})
return HttpResponse(t.render(c))
def menu(request):
TITRE_PAGE = "MENU PRINCIPAL"
t = loader.get_template('tmpl/menu.html')
d = datetime.datetime.now()
PUB_DATE = d.strftime("%d/%m/%Y %X")
menu = [
('fex/' , 'Gestions des Echanges de fichiers'),
('put_file' , 'Déposer un fichier'),
('get_file' , 'Récuperer un fichier'),
('param' , 'Paramètre Généraux'),
]
c = Context({
'PUB_DATE':PUB_DATE,
'TITRE_PAGE' : TITRE_PAGE,
'menu_items' : menu
})
return HttpResponse(t.render(c))
def put_file(request):
return HttpResponse("NON IMPLEMENTEE : put_file")
def get_file(request):
return HttpResponse("NON IMPLEMENTEE : get_file")
def param(request):
return HttpResponse("NON IMPLEMENTEE : param")
| Python |
"""
WSGI config for filex project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "filex.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
| Python |
# -*- coding: utf-8 -*-
from django.db import models
from django import forms
from django.views.generic import CreateView
from django.utils.translation import ugettext_lazy as _
# Create your models here.
TYPE_ENT = (
( 'ROOT' , 'ROOT' ),
( 'TIERS', 'TIERS'),
)
class EntiteClass(models.Model):
codent = models.CharField(_(u'Code Entite'),max_length=20, unique=True)
noment = models.CharField(_(u'Nom Entite'),max_length=40)
description = models.TextField(_(u'Description'))
typent = models.CharField(_(u'Type Entite'), max_length=10, choices=TYPE_ENT )
def __unicode__(self):
return "%s : %s" % (self.codent, self.noment)
class EntiteForm(forms.Form):
codent = forms.CharField(label='Code Entité ',max_length=20)
noment = forms.CharField(label='Nom Entité ',max_length=40)
description = forms.CharField(label='Description ', widget=forms.Textarea)
typent = forms.ChoiceField( label='Type Entité ',choices=TYPE_ENT)
class UtilisateurClass(models.Model):
codusr = models.CharField(_(u'Code Utilisateur'),max_length=20, unique=True)
nomusr = models.CharField(_(u'Nom Utilisateur'),max_length=40)
email_usr = models.EmailField(_(u'Email'))
tiers_usr = models.ForeignKey(EntiteClass)
def __unicode__(self):
return "%s : %s" % (self.codusr, self.nomusr)
class UtilisateurForm(forms.Form):
codusr = forms.CharField(label='Code Utilisateur ',max_length=20)
nomusr = forms.CharField(label='Nom Utilisateur ',max_length=40)
email_usr = forms.EmailField(label='E-mail ')
tiers_usr = forms.CharField(label='Tiers ',max_length=20)
| 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 |
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from models import UtilisateurClass
urlpatterns = patterns('fex.views',
# Examples:
# url(r'^$', 'filex.views.home', name='home'),
# url(r'^filex/', include('filex.foo.urls')),
# fex => Entite
url(r'^$', 'fex_liste', name='ges_fex' ),
url(r'^cr$', 'fex_create', name='fex_create' ),
url(r'^(?P<fex_id>\d+)/$', 'fex_detail', name='fex_detail' ),
# fex => User
url(r'^usr/$', 'fex_usr_liste', name='fex_ls_usr' ),
url(r'^liste/$', 'fex_std_liste', { 'model':UtilisateurClass, 'template':'tmpl/fex/list_usr.html', 'p':2, }),
)
| Python |
# -*- coding: utf-8 -*-
from django.contrib import admin
from fex.models import EntiteClass, UtilisateurClass
admin.site.register(EntiteClass)
admin.site.register(UtilisateurClass)
| Python |
# -*- coding: utf-8 -*-
# Create your views here.
from django.template import Context, loader
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, get_list_or_404
from django.shortcuts import render, render_to_response
from django.shortcuts import HttpResponseRedirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from models import EntiteClass
from models import EntiteForm
from models import UtilisateurClass
from models import UtilisateurForm
from django import forms
import datetime
import pdb
def get_pub_date():
d = datetime.datetime.now()
return d.strftime("%d/%m/%Y %X")
def test_fex_liste(request):
return HttpResponse("NON IMPLEMENTEE : ges_fex => liste ")
def test_fex_detail(request, fex_id):
return HttpResponse("NON IMPLEMENTEE : fex_detail => %s" % fex_id)
def fex_liste(request):
TITRE_PAGE = "FLEX EXCHANGE DETAIL / LISTE"
t = loader.get_template('tmpl/fex/liste.html')
d = datetime.datetime.now()
PUB_DATE = d.strftime("%d/%m/%Y %X")
e = EntiteClass.objects.all()
#e = get_list_or_404(EntiteClass, typent='TIERS')
c = Context({
'PUB_DATE':PUB_DATE,
'TITRE_PAGE' : TITRE_PAGE,
'all_e' : e,
})
return HttpResponse(t.render(c))
def fex_detail(request, fex_id):
TITRE_PAGE = "FLEX EXCHANGE DETAIL"
t = loader.get_template('tmpl/fex/detail.html')
d = datetime.datetime.now()
PUB_DATE = d.strftime("%d/%m/%Y %X")
#e = get_object_or_404(EntiteClass, pk=fex_id)
e = EntiteClass.objects.get(id=fex_id)
c = Context({
'PUB_DATE':PUB_DATE,
'TITRE_PAGE' : TITRE_PAGE,
'entite' : e,
})
return HttpResponse(t.render(c))
def fex_create(request):
if request.method == 'POST':
## Bouton VALID
if request.POST['VALID'] == 'VALID':
#pdb.set_trace()
f = EntiteForm(request.POST)
if f.is_valid():
new_ent = EntiteClass()
##
new_codent = f.cleaned_data['codent']
q = EntiteClass.objects.get(codent=new_codent)
if q:
f.errors['__all__'] = f.error_class(["Cle Deja Existante"])
else:
new_ent.noment = f.cleaned_data['noment']
new_ent.description = f.cleaned_data['description']
new_ent.typent = f.cleaned_data['typent']
new_ent.save()
return HttpResponseRedirect('/fex')
else:
## Bouton ANNUL
return HttpResponseRedirect('/fex')
else:
f = EntiteForm()
return render( request, 'tmpl/fex/fex_create.html', { 'form' : f, 'PUB_DATE':get_pub_date() } )
def fex_usr_liste(request):
obj_list = UtilisateurClass.objects.all()
paginator = Paginator(obj_list, 10)
page = request.GET.get('page')
try:
objs = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
objs = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
objs = paginator.page(paginator.num_pages)
return render_to_response('tmpl/fex/list_usr.html', {"objs": objs})
## --------------------------------
## Liste Standard avec pagination
## --------------------------------
def fex_std_liste(request, model, template, p=10):
d = datetime.datetime.now()
PUB_DATE = d.strftime("%d/%m/%Y %X")
obj_list = model.objects.all()
paginator = Paginator(obj_list, p)
page = request.GET.get('page')
try:
objs = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
objs = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
objs = paginator.page(paginator.num_pages)
return render_to_response(template, {"objs": objs, 'PUB_DATE':PUB_DATE })
| Python |
# Copyright (C) 2010 Razvan Constantin <razvan.constantin@rconst.net>
#
# This file is part of FileBow.
#
# FileBow is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# FileBow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with FileBow. If not, see <http:#www.gnu.org/licenses/>.
# WAF builder extensions customized for filebow
import Options
def library(self, lib):
self.lib = lib
self.lib_objs = []
def abs_target_name(self, name):
if '#' not in name:
return self.lib + '#' + name
return name
def build_target(self, name, deps = (), libs = ('POCO', ), test = False):
libname = self.abs_target_name(name)
local_deps = ' '.join([self.abs_target_name(dep) for dep in deps])
self.new_task_gen(
features = 'cxx cstaticlib',
name = libname,
target = libname,
source = [ name + '.cpp' ],
includes = self.srcnode.abspath(),
uselib = ' '.join(libs),
uselib_local = local_deps,
install_path = None)
if test and Options.options.test:
testname = libname + '.test'
self.new_task_gen(
features = 'cxx cprogram crun',
name = testname,
target = testname,
source = [ name + '_test.cpp' ],
includes = self.srcnode.abspath(),
uselib_local = libname + ' testing#test_main testing#test_drive ' + local_deps,
install_path = None)
def build_plugin(self, name, main, deps):
""" Builds the plugin shared library to be copied in the Geany plugins folder """
env = self.env
plugin_env = env.copy()
plugin_env['shlib_PATTERN'] = '%s'
self.set_env('default', plugin_env)
self.new_task_gen(
features = 'cxx cshlib',
name = name,
target = '%s.so' % name,
source = [ main ],
uselib = 'GEANY GTK POCO',
uselib_local = ' '.join(deps),
install_path = self.env['GEANY_PLUGINS'])
self.set_env('default', env)
def extend(bld):
import types
for fn in (abs_target_name, library, build_target, build_plugin):
setattr(bld, fn.__name__, types.MethodType(fn, bld))
| Python |
# Copyright (C) 2010 Razvan Constantin <razvan.constantin@rconst.net>
#
# This file is part of FileBow.
#
# FileBow is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# FileBow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with FileBow. If not, see <http:#www.gnu.org/licenses/>.
# Build script for FileBow testing utilities.
import Options
def configure(conf):
pass
def build(bld):
if not Options.options.test:
return
bld.library('testing')
bld.build_target(
name = 'test_drive',
test = True
)
bld.build_target(
name = 'test_main',
deps = ('common#common', ),
libs = ('GTEST', ),
test = False
)
| Python |
# Copyright (C) 2010 Razvan Constantin <razvan.constantin@rconst.net>
#
# This file is part of FileBow.
#
# FileBow is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# FileBow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with FileBow. If not, see <http:#www.gnu.org/licenses/>.
# WAF configurator extensions customized for filebow
import os.path
import Options
def configure_poco(self):
""" Check for existence of poco libraries """
self.check_cxx(
lib='PocoFoundation',
uselib_store='POCO',
mandatory=True,
args='--libs')
def configure_gtk(self):
""" Check for existence of gtk libraries """
self.check_cfg(
package='gtk+-2.0',
atleast_version='2.6.0',
uselib_store='GTK',
mandatory=True,
args='--cflags --libs',
path=self.env['CFG_TOOL'])
def configure_geany(self):
""" Check for existence of geany headers """
GEANY_PREFIX = self.env['GEANY_INCLUDES']
GEANY_INCLUDES = [os.path.join(GEANY_PREFIX, INCLUDE) for INCLUDE in ('', 'scintilla', 'tagmanager')]
self.check_cc(
header_name='geanyplugin.h',
mandatory=True,
defines=['GTK'],
uselib='GTK',
uselib_store='GEANY',
includes=GEANY_INCLUDES + [self.srcdir,])
def configure_gtest(self):
""" Check for existence of gtest libraries """
self.check_cxx(
header_name='gtest/gtest.h',
uselib_store='GTEST')
self.env.LIB_GTEST = 'gtest'
def extend(conf):
import types
for fn in (configure_poco, configure_gtk, configure_geany, configure_gtest):
setattr(conf, fn.__name__, types.MethodType(fn, conf))
| Python |
# Copyright (C) 2010 Razvan Constantin <razvan.constantin@rconst.net>
#
# This file is part of FileBow.
#
# FileBow is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# FileBow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with FileBow. If not, see <http:#www.gnu.org/licenses/>.
# Build script for Geany File Navigator logic.
def configure(conf):
pass
def build(bld):
bld.library('logic')
bld.build_target(
name = 'file_filter',
deps = ('common#common', 'path-tree', ),
test = True)
bld.build_target(
name = 'file-scorer',
deps = ('common#common', 'common#strings', 'path-tree', ),
test = True)
bld.build_target(
name = 'history',
deps = ('file-scorer', 'common#common', 'common#strings', 'path-tree',
'utils#npath', ),
test = True)
bld.build_target(
name = 'navigator',
deps = ('common#common', 'common#strings', 'history', 'file-scorer',
'path-tree', 'file_filter', 'top_builder', 'path-scanner',
'utils#npath', ),
test = True)
bld.build_target(
name = 'path-scanner',
deps = ('common#common', 'common#strings', 'path-tree', ),
libs = ('GTK', 'POCO',),
test = True)
bld.build_target(
name = 'path-tree',
deps = ('common#common', 'common#strings'),
test = True)
bld.build_target(
name = 'top_builder',
deps = ('common#common', 'file_filter', 'file-scorer', 'path-tree', ),
test = True)
| Python |
# Copyright (C) 2010 Razvan Constantin <razvan.constantin@rconst.net>
#
# This file is part of FileBow.
#
# FileBow is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# FileBow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with FileBow. If not, see <http:#www.gnu.org/licenses/>.
# Build script for Geany File Navigator utils.
def configure(conf):
pass
def build(bld):
bld.library('utils')
bld.build_target(
name = 'npath',
deps = (
'common#common',
),
test = True)
| Python |
###
# Copyright (C) 2010 Razvan Constantin <razvan.constantin@rconst.net>
#
# This file is part of FileBow.
#
# FileBow is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# FileBow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with FileBow. If not, see <http:#www.gnu.org/licenses/>.
###
# Main build script for Geany FileBow Plugin.
#
# To build and install Geany FileBow plugin run:
# ./waf configure
# ./waf build
# ./waf build --test # Builds and run unittests
# sudo ./waf install
#
# Additional configuration options:
# --geany-includes[=/usr/local/include/geany] prefix location for geany includes
# --geany-plugins[=/usr/local/lib/geany] plugins base
#
# Unit tests can be build and executed using:
# ./waf build --test
APPNAME = 'FileBow'
VERSION = '0.1'
srcdir = '.'
blddir = 'build'
### Imports
import Options
import Utils
import crun
import builder
import configurator
### Build specification
def set_options(opt):
opt.tool_options('compiler_cxx compiler_cc')
opt.add_option('--cfg-tool', default='pkg-config',
help='Alternative tool/path for pkg-config (gtk discovery)',
action='store', dest='cfg_tool', type='string')
opt.add_option('--geany-includes', default='/usr/local/include/geany',
help='Geany include directory',
action='store', dest='geany_includes', type='string')
opt.add_option('--geany-plugins', default='/usr/local/lib/geany',
help='Geany plugin directory',
action='store', dest='geany_plugins', type='string')
opt.add_option('--test', default=False, action='store_true')
def configure(conf):
conf.check_tool('compiler_cxx compiler_cc')
conf.env['CXXFLAGS'] = [ '-fPIC' ]
conf.env['CCFLAGS'] = [ '-fPIC' ]
conf.env['CFG_TOOL'] = Options.options.cfg_tool
conf.env['GEANY_INCLUDES'] = Options.options.geany_includes
conf.env['GEANY_PLUGINS'] = Options.options.geany_plugins
configurator.extend(conf)
conf.configure_poco()
conf.configure_gtest()
conf.recurse('common logic testing ui utils')
def build(bld):
builder.extend(bld)
bld.recurse('common logic testing ui utils')
bld.build_plugin('filebow',
'ui/filebow.cpp',
deps = ('ui#plugin', 'ui#geany-bridge',))
def shutdown():
pass
| Python |
# Copyright (C) 2010 Razvan Constantin <razvan.constantin@rconst.net>
#
# This file is part of FileBow.
#
# FileBow is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# FileBow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with FileBow. If not, see <http:#www.gnu.org/licenses/>.
# WAF task extensions for running a cxx program after link.
import TaskGen
import Task
import Logs
@TaskGen.taskgen
@TaskGen.feature('crun')
@TaskGen.after('apply_link')
def crun(self):
""" Executes a cprogram target after it has been built. """
if not 'cprogram' in self.features:
Logs.error('Only cprogram can be executed %s' % self)
return
task = cxx_run(self.env.copy(), self)
task.set_inputs(self.link_task.outputs)
class cxx_run(Task.Task):
def __init__(self, env, generator):
Task.Task.__init__(self, env, generator=generator)
def run(self):
for input in self.inputs:
cmd = input.abspath(self.env)
cmd_dir = input.parent.abspath(self.env)
Logs.debug('Running %s in %s' % (cmd, cmd_dir))
self.exec_command(cmd, cwd = cmd_dir)
return 0
quiet = 1
after = [ 'cxx_link', 'cc_link' ]
Task.always_run(cxx_run)
| Python |
# Copyright (C) 2010 Razvan Constantin <razvan.constantin@rconst.net>
#
# This file is part of FileBow.
#
# FileBow is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# FileBow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with FileBow. If not, see <http:#www.gnu.org/licenses/>.
# Build script for FileBow common library.
def configure(conf):
pass
def build(bld):
bld.library('common')
bld.build_target(
name = 'common',
test = True
)
bld.build_target(
name = 'strings',
deps = (
'common',
),
test = True
)
| Python |
# Copyright (C) 2010 Razvan Constantin <razvan.constantin@rconst.net>
#
# This file is part of FileBow.
#
# FileBow is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# FileBow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with FileBow. If not, see <http:#www.gnu.org/licenses/>.
# Build script for Geany FileBow plugin.
import Options
def configure(conf):
conf.configure_gtk()
conf.configure_geany()
def build(bld):
bld.library('ui')
bld.new_task_gen(
features = 'cc cstaticlib',
name = 'ui#geany-bridge',
target = 'ui#geany-bridge',
source = [ 'geany-bridge.c' ],
includes = bld.srcnode.abspath(),
uselib = 'GTK GEANY',
install_path = None)
bld.build_target(
name = 'navigate-dlg',
deps = ('geany-bridge', 'common#common', 'logic#navigator'),
libs = ('GTK', 'POCO',),
test = False)
bld.build_target(
name = 'plugin',
deps = ('navigate-dlg', 'common#common', 'logic#navigator'),
libs = ('GTK', 'POCO',),
test = False)
if Options.options.test:
bld.new_task_gen(
features = 'cxx cprogram',
name = 'navigate-dlg.test',
target = 'ui#navigate-dlg.test',
source = [ 'navigate-dlg.cpp', 'navigate-dlg_test.cpp' ],
uselib = 'POCO GTK GEANY',
includes = bld.srcnode.abspath(),
defines = [ 'NAVIGATE_DLG_TEST' ],
uselib_local = 'common#common logic#navigator common#strings',
install_path = None)
| Python |
import gtk
import urllib
import os
TARGET_TYPE_URI_LIST = 80
dnd_list = [ ( 'text/uri-list', 0, TARGET_TYPE_URI_LIST ) ]
def get_file_path_from_dnd_dropped_uri(uri):
# get the path to file
path = ""
if uri.startswith('file:\\\\\\'): # windows
path = uri[8:] # 8 is len('file:///')
elif uri.startswith('file://'): # nautilus, rox
path = uri[7:] # 7 is len('file://')
elif uri.startswith('file:'): # xffm
path = uri[5:] # 5 is len('file:')
path = urllib.url2pathname(path) # escape special chars
path = path.strip('\r\n\x00') # remove \r\n and NULL
return path
def on_drag_data_received(widget, context, x, y, selection, target_type, timestamp):
print selection.data.strip('\r\n\x00')
if target_type == TARGET_TYPE_URI_LIST:
uri = selection.data.strip('\r\n\x00')
print 'uri', uri
uri_splitted = uri.split() # we may have more than one file dropped
for uri in uri_splitted:
path = get_file_path_from_dnd_dropped_uri(uri)
print 'path to open', path
if os.path.isfile(path): # is it file?
data = file(path).read()
print data
w = gtk.Window()
w.connect('drag_data_received', on_drag_data_received)
w.drag_dest_set( gtk.DEST_DEFAULT_MOTION |
gtk.DEST_DEFAULT_HIGHLIGHT | gtk.DEST_DEFAULT_DROP,
dnd_list, gtk.gdk.ACTION_COPY)
w.show_all()
gtk.main()
| Python |
"""
This file provides basic operations support on Google Storage.
Currently, upload/download/delete operations are supported.
"""
import os, sys
import tempfile
import hashlib
sys.path.append('./boto')
import boto
from env import *
from boto.exception import GSResponseError
from boto.exception import InvalidUriError
"Get your developer keys from the .boto config file."
config = boto.config
def upload_file(fullname, dst_name):
"""
This function upload file to Google Storage bucket: ollir-cp.
@example
fullname: /tmp/dir/a.txt
dst_name: dir/a.txt
"""
"Create source and destination URIs."
src_uri = boto.storage_uri(fullname, "file")
dst_uri = boto.storage_uri(bucket_name, "gs")
"Create a new destination URI with the source file name as the object name."
new_dst_uri = dst_uri.clone_replace_name(dst_name)
"Create a new destination key object."
dst_key = new_dst_uri.new_key()
"Retrieve the source key and create a source key object."
src_key = src_uri.get_key()
"Create a temporary file to hold your copy operation."
tmp = tempfile.TemporaryFile()
src_key.get_file(tmp)
tmp.seek(0)
"Upload the file."
dst_key.set_contents_from_file(tmp)
def ls_remote_file(email_address):
filedir=[]
dst_uri = boto.storage_uri(bucket_name, "gs")
"objs = dst_uri.get_bucket()"
for obj in dst_uri.get_all_keys():
entry_list = obj.get_acl().entries.entry_list
for entry in entry_list:
if email_address == entry.scope.email_address and entry.permission in file_permissions:
"print obj.name"
filedir.append(obj.name)
break
return filedir
def _get_md5(file):
f = open(file).read()
m = hashlib.md5()
m.update(f)
return m.hexdigest()
def compare_file_meta(dst_name):
"""
This function compare the local file and remote file, return one of the following status:
['local_not_exists', 'remote_not_exists', 'synced', 'local_newer', 'remote_newer']
"""
local_file = os.path.join(local_dir, dst_name)
if not os.path.exists(local_file):
return 'local_not_exists'
try:
dst_uri = boto.storage_uri(bucket_name, "gs")
new_dst_uri = dst_uri.clone_replace_name(dst_name)
file_key = new_dst_uri.get_key()
except InvalidUriError:
return 'remote_not_exists'
local_md5 = _get_md5(local_file)
remote_md5 = file_key.etag.strip('"\'')
if local_md5 == remote_md5:
return 'synced'
def set_access_permission(dst_name, email_address, permission="FULL_CONTROL"):
"""
This function set the file permission.
"""
dst_uri = boto.storage_uri(bucket_name, "gs")
new_dst_uri = dst_uri.clone_replace_name(dst_name)
if permission in file_permissions:
new_dst_uri.add_email_grant(permission, email_address)
def download_file(src_file, dst_path):
"""
This function download file from GS, and put it to dest_path.
@example
src_file: dir/a.txt
dst_path: /tmp
=> /tmp/dir/a.txt
"""
"Download the files."
src_uri = boto.storage_uri(bucket_name + "/" + src_file, "gs")
dst_uri = boto.storage_uri(dst_path, "file")
"Append the object name to the directory name."
dst_key_name = dst_uri.object_name + os.sep + src_uri.object_name
"Use the new destination key name to create a new destination URI."
new_dst_uri = dst_uri.clone_replace_name(dst_key_name)
"Create a new destination key object."
dst_key = new_dst_uri.new_key()
"Retrieve the source key and create a source key object."
src_key = src_uri.get_key()
"Create a temporary file to hold our copy operation."
tmp = tempfile.TemporaryFile()
src_key.get_file(tmp)
tmp.seek(0)
"Download the object."
dst_key.set_contents_from_file(tmp)
def delete_file(src_file):
"""
This function delete a file.
"""
"Create a URI for a bucket."
uri = boto.storage_uri(bucket_name, "gs")
"Get the objects that are in the bucket."
objs = uri.get_bucket()
"Delete the objects first, then the bucket."
if objs:
for obj in objs:
if obj.name == src_file:
obj.delete()
if __name__ == '__main__':
if sys.argv[1] == 'upload':
file_names = sys.argv[2:]
for fullname in file_names:
basename = os.path.basename(os.path.abspath(fullname))
upload_file(fullname, basename)
set_access_permission(basename, email_address, "FULL_CONTROL")
elif sys.argv[1] == 'download':
file_names = sys.argv[2:-1]
dst_path = sys.argv[-1]
for file in file_names:
download_file(file, dst_path)
elif sys.argv[1] == 'ls':
ls_remote_file(email_address)
elif sys.argv[1] == 'delete':
file_names = sys.argv[2:]
for file in file_names:
delete_file(file)
elif sys.argv[1] == 'check':
file_names = sys.argv[2:]
for file in file_names:
print compare_file_meta(file)
| Python |
email_address = 'ollir.h@gmail.com'
file_permissions = [u'READ', u'FULL_CONTROL']
"bucket_name for public usage."
bucket_name = "ollir-cp"
local_dir = "/home/zhango/fileplace_dir"
| Python |
"""
This file keep syncing local directory and Google Storage.
"""
import os,sys
import shutil
import operations
from env import *
def set_local_dir(path):
if os.path.exists(path):
if os.path.isdir(path):
local_dir = path
else:
return False
else:
os.makedirs(path)
local_dir = path
def local_dir_available():
if os.path.isdir(local_dir):
return True
else:
return False
def add_local_file(src_file, dst_file):
"""
This function copy the source file/directory to the local_dir.
@dst_file: relative path
@example
src_file: /tmp/dir/a.txt
dst_file: a.txt
-----------------
src_file: /tmp/dir/
dst_file: dir
"""
if local_dir_available():
dst_fullname = os.path.join(local_dir, dst_file)
if os.path.isdir(src_file):
shutil.copytree(src_file, dst_fullname)
elif os.path.isfile(src_file):
shutil.copyfile(src_file, dst_fullname)
else:
return False
def move_local_file(src_file, dst_file):
"""
This function copy the src_file in local_dir to a given place.
@example
src_file: dir/a.txt
dst_file: /tmp/a.txt
-----------------
src_file: dir
dst_file: /tmp/dir
"""
src_fullpath = os.path.join(local_dir, src_file)
if os.path.isdir(src_fullpath):
shutil.copytree(src_fullpath, dst_file)
elif os.path.isfile(src_fullpath):
shutil.copyfile(src_fullpath, dst_file)
def del_local_file(src_file):
"""
@example
src_file: dir/a.txt
-----------------
src_file: dir
"""
fullpath = os.path.join(local_dir, src_file)
if os.path.isdir(fullpath):
shutil.rmtree(fullpath)
elif os.path.isfile(fullpath):
os.remove(fullpath)
def sync():
pass
def add_remote_file(src_file):
"""
This function upload local file/directory to remote cloud.
@example
src_file: /tmp/dir/a.txt
-----------------
src_file: /tmp/dir/
"""
if os.path.isfile(src_file):
operations.upload_file(src_file, os.path.basename(src_file))
elif os.path.isdir(src_file):
dir_prefix = os.path.dirname(os.path.abspath(src_file))
for root, dirs, files in os.walk(src_file, topdown=False):
for name in files:
full_path = os.path.abspath(os.path.join(root, name))
rel_file = full_path[len(dir_prefix)+1:]
print ">>> Uploading "+rel_file
operations.upload_file(full_path, rel_file)
operations.set_access_permission(rel_file, email_address, "FULL_CONTROL")
def rm_remote_file():
pass
def ls_remote_file(email_address):
return operations.ls_remote_file(email_address)
def check_file_status():
"""
This call would sync with the GS server to see if the given file is up to date.
According to md5 check & time comparing.
@status: up-to-date/local-new/remote-new/uploading
"""
pass
if __name__ == '__main__':
if sys.argv[1] == 'upload':
file_names = sys.argv[2:]
for fullname in file_names:
add_remote_file(fullname)
elif sys.argv[1] == 'ls':
print ls_remote_file(email_address)
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1292508978.846772
_template_filename='/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/search/content.mako'
_template_uri='search/content.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
c = context.get('c', UNDEFINED)
request = context.get('request', UNDEFINED)
__M_writer = context.writer()
# SOURCE LINE 1
__M_writer(u'<style type="text/css">\n\t#search_options label{width:60px;}\n\t#form_search #submit{\n\t\tbackground:url(\'/image/global/button_search.png\') no-repeat scroll 0 0 transparent;\n\t\tmargin-top:5px;\n\t\twidth:60px;\n\t\theight:30px;\n\t\tcursor:pointer;\n\t\tfloat:right;\n\t}\n\t#form_search #submit:hover{background:url(\'/image/global/button_search.png\') no-repeat scroll 0 -30px transparent;}\n\t#bottom_nav{\n\t\theight:25px;\n\t\twidth:100%;\n\t}\n\t#button_last_page{\n\t\tbackground:url(\'/image/global/button_last_page.png\') no-repeat scroll 0 0 transparent;\n\t\twidth:60px;\n\t\theight:25px;\n\t\tcursor:pointer;\n\t\tfloat:right;\n\t}\n\t#button_last_page:hover{background:url(\'/image/global/button_last_page.png\') no-repeat scroll 0 -25px transparent;}\n\t#button_next_page{\n\t\tbackground:url(\'/image/global/button_next_page.png\') no-repeat scroll 0 0 transparent;\n\t\twidth:60px;\n\t\theight:25px;\n\t\tcursor:pointer;\n\t\tfloat:right;\n\t}\n\t#button_next_page:hover{background:url(\'/image/global/button_next_page.png\') no-repeat scroll 0 -25px transparent;}\n\t.result_item{cursor:pointer;}\n\t.result_item:hover{background-color:#F9F9F9;}\n</style>\n<script type="text/javascript">\n\t$(document).ready(function(){\n\t\tvar pageId = parseInt($("#form_search #input_page").val());\n\t\t$("#form_search #input_page").val(0);\n\t\t$("#search_options #type" + ')
# SOURCE LINE 39
__M_writer(filters.decode.utf8(c.searchType))
__M_writer(u').attr("checked", "checked");\n\t\t$("#search_options").buttonset();\n\t\t$("#form_search #submit").click(function(){$("#form_search").submit();});\n\t\tif ($("#button_last_page").size()){\n\t\t\t$("#button_last_page").click(function(){\n\t\t\t\t$("#form_search #input_page").val(pageId - 1);\n\t\t\t\t$("#form_search").submit();\n\t\t\t});\n\t\t}\n\t\tif ($("#button_next_page").size()){\n\t\t\t$("#button_next_page").click(function(){\n\t\t\t\t$("#form_search #input_page").val(pageId + 1);\n\t\t\t\t$("#form_search").submit();\n\t\t\t});\n\t\t}\n\t\t$(".result_item").click(function(){window.location = $(this).attr("alt");});\n\t});\n</script>\n<div id="search_bound">\n\t<h1>\u641c\u7d22</h1>\n\t<div class="page_column_left_padding15">\n\t\t<div class="top"></div>\n\t\t<div class="content">\n\t\t\t<form id="form_search" action="/search" method="get">\n\t\t\t\t<div>\n\t\t\t\t\t<label>\u5173\u952e\u5b57</label>\n')
# SOURCE LINE 65
if 'q' in request.GET :
# SOURCE LINE 66
__M_writer(u'\t\t\t\t\t\t<input name="q" value="')
__M_writer(filters.decode.utf8(request.GET['q']))
__M_writer(u'"></input>\n')
# SOURCE LINE 67
else :
# SOURCE LINE 68
__M_writer(u'\t\t\t\t\t\t<input name="q"></input>\n')
pass
# SOURCE LINE 70
__M_writer(u'\t\t\t\t</div>\n\t\t\t\t<div>\n\t\t\t\t\t<label>\u641c\u7d22\u9009\u9879</label>\n\t\t\t\t\t<span id="search_options">\n\t\t\t\t\t\t<input type="radio" id="type1" name="type" value="1"/><label for="type1">\u5730\u70b9</label>\n\t\t\t\t\t\t<input type="radio" id="type2" name="type" value="2"/><label for="type2">\u8bdd\u9898</label>\n\t\t\t\t\t\t<input type="radio" id="type3" name="type" value="3"/><label for="type3">\u4f18\u60e0</label>\n\t\t\t\t\t</span>\n\t\t\t\t\t<span id="submit"></span>\n\t\t\t\t</div>\n\t\t\t\t<input type="hidden" name="page" value="')
# SOURCE LINE 80
__M_writer(filters.decode.utf8(c.page))
__M_writer(u'" id="input_page"></input>\n\t\t\t</form>\n')
# SOURCE LINE 82
if c.errMsg == 'too fast' :
# SOURCE LINE 83
__M_writer(u'\t\t\t\t<div style="width:100%;height:20px;clear:both;"></div>\n\t\t\t\t<h2>\u60a8\u7684\u641c\u7d22\u8bf7\u6c42\u63d0\u4ea4\u8fc7\u4e8e\u9891\u7e41\uff0c\u8bf7\u7a0d\u5019\u518d\u8bd5\u3002</h2>\n')
# SOURCE LINE 85
elif c.result != None :
# SOURCE LINE 86
__M_writer(u'\t\t\t\t<div style="width:100%;height:20px;clear:both;"></div>\n\t\t\t\t<h2>\u641c\u7d22\u7ed3\u679c</h2>\n\t\t\t\t<div style="width:100%;height:5px;clear:both;"></div>\n')
# SOURCE LINE 89
if c.resultCount == 0 :
# SOURCE LINE 90
__M_writer(u'\t\t\t\t\t<div style="margin-left:10px;">\u641c\u7d22\u7ed3\u679c\u4e3a\u7a7a\u3002</div>\n')
# SOURCE LINE 91
else :
# SOURCE LINE 92
if c.searchType == '1' :
# SOURCE LINE 93
for r in c.result :
# SOURCE LINE 94
__M_writer(u'\t\t\t\t\t\t\t<div class="result_item" style="border-top:1px solid #EEEEEE;padding:5px;" alt="/map/maploc?id=')
__M_writer(filters.decode.utf8(r.id))
__M_writer(u'">\n\t\t\t\t\t\t\t\t<div style="font-size:14px;font-weight:bold;">')
# SOURCE LINE 95
__M_writer(filters.decode.utf8(r.name))
__M_writer(u'</div>\n\t\t\t\t\t\t\t\t<div>')
# SOURCE LINE 96
__M_writer(filters.decode.utf8(r.address))
__M_writer(u'</div>\n\t\t\t\t\t\t\t</div>\n')
pass
# SOURCE LINE 99
elif c.searchType == '2' :
# SOURCE LINE 100
for r in c.result :
# SOURCE LINE 101
__M_writer(u'\t\t\t\t\t\t\t<div class="result_item" style="border-top:1px solid #EEEEEE;padding:5px;" alt="/map/maploc/topic?id=')
__M_writer(filters.decode.utf8(r.id))
__M_writer(u'">\n\t\t\t\t\t\t\t\t<div style="font-size:14px;font-weight:bold;">')
# SOURCE LINE 102
__M_writer(filters.decode.utf8(r.title))
__M_writer(u'</div>\n\t\t\t\t\t\t\t\t<div>By ')
# SOURCE LINE 103
__M_writer(filters.decode.utf8(r.user.name))
__M_writer(u'</div>\n\t\t\t\t\t\t\t</div>\n')
pass
# SOURCE LINE 106
elif c.searchType == '3' :
# SOURCE LINE 107
for r in c.result :
# SOURCE LINE 108
__M_writer(u'\t\t\t\t\t\t\t<div class="result_item" style="border-top:1px solid #EEEEEE;padding:5px;" alt="/map/maploc?id=')
__M_writer(filters.decode.utf8(r.store.id))
__M_writer(u'">\n\t\t\t\t\t\t\t\t<div style="font-size:14px;font-weight:bold;">')
# SOURCE LINE 109
__M_writer(filters.decode.utf8(r.name))
__M_writer(u'</div>\n\t\t\t\t\t\t\t\t<div>\u5546\u6237\uff1a')
# SOURCE LINE 110
__M_writer(filters.decode.utf8(r.store.mapLoc.name))
__M_writer(u'</div>\n\t\t\t\t\t\t\t</div>\n')
pass
pass
pass
# SOURCE LINE 115
if c.page * 20 + 20 < c.resultCount or c.page > 0 :
# SOURCE LINE 116
__M_writer(u'\t\t\t\t\t<div id="bottom_nav">\n\t\t\t\t\t\t<span style="float:left;color:#666666;">\u7b2c')
# SOURCE LINE 117
__M_writer(filters.decode.utf8(c.page + 1))
__M_writer(u'\u9875\uff0c\u5171')
__M_writer(filters.decode.utf8((c.resultCount - 1) / 20 + 1))
__M_writer(u'\u9875</span>\n')
# SOURCE LINE 118
if c.page * 20 + 20 < c.resultCount :
# SOURCE LINE 119
__M_writer(u'\t\t\t\t\t\t\t<span id="button_next_page"></span>\n')
pass
# SOURCE LINE 121
__M_writer(u'\t\t\t\t\t\t<span style="float:right;width:10px;height:10px;"></span>\n')
# SOURCE LINE 122
if c.page > 0 :
# SOURCE LINE 123
__M_writer(u'\t\t\t\t\t\t\t<span id="button_last_page"></span>\n')
pass
# SOURCE LINE 125
__M_writer(u'\t\t\t\t\t</div>\n')
pass
pass
# SOURCE LINE 128
__M_writer(u'\t\t</div>\n\t\t<div class="bottom"></div>\n\t</div>\n\t<div class="page_column_right_padding_left30">\n\t\t<div class="top"></div>\n\t\t<div class="content">\n\t\t\t<h2>TIPS</h2>\n\t\t\t<p>\u641c\u7d22\u65f6\uff0c\u60a8\u53ef\u4ee5\u8f93\u5165\u591a\u4e2a\u5173\u952e\u8bcd\uff0c\u4e2d\u95f4\u7528\u7a7a\u683c\u9694\u5f00\u3002</p>\n\t\t</div>\n\t\t<div class="bottom"></div>\n\t</div>\n</div>\n')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1293190608.75337
_template_filename='/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/map/maploc.mako'
_template_uri='map/maploc.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
c = context.get('c', UNDEFINED)
__M_writer = context.writer()
# SOURCE LINE 1
c.jsFiles.append('/script/map/maploc.js?v=10')
# SOURCE LINE 3
__M_writer(u'\n<style type="text/css">\n\t#topiclist tr{cursor:pointer;}\n\t#topiclist tr:hover{background-color:#F9F9F9;}\n\t#button_add_topic{\n\t\tfloat:right;\n\t\twidth:80px;\n\t\theight:25px;\n\t\tbackground:url(\'/image/global/button_add_topic.png\');\n\t}\n\t#button_add_topic:hover{background-position:0 -25px;}\n\t#link_return{\n\t\tfloat:left;\n\t\twidth:60px;\n\t\theight:25px;\n\t\tbackground:url(\'/image/global/button_return.png\');\n\t}\n\t#link_return:hover{background-position:0 -25px;}\n</style>\n<div class="page_variable">\n\t<div var_name="info" id="')
# SOURCE LINE 23
__M_writer(filters.decode.utf8(c.maploc.id))
__M_writer(u'" maploc_id="')
__M_writer(filters.decode.utf8(c.maploc.id))
__M_writer(u'" name="')
__M_writer(filters.decode.utf8(c.maploc.name))
__M_writer(u'" address="')
__M_writer(filters.decode.utf8(c.maploc.address))
__M_writer(u'"\n\t\ttopic_count="')
# SOURCE LINE 24
__M_writer(filters.decode.utf8(c.topicCount))
__M_writer(u'" rate_count="')
__M_writer(filters.decode.utf8(c.rateCount))
__M_writer(u'" total_rate_score="')
__M_writer(filters.decode.utf8(c.totalRateScore))
__M_writer(u'"\n')
# SOURCE LINE 25
if c.loginUser != None :
# SOURCE LINE 26
__M_writer(u'\t\t\tmy_rating="')
__M_writer(filters.decode.utf8(c.myRating))
__M_writer(u'"\n')
pass
# SOURCE LINE 28
__M_writer(u'\t></div>\n</div>\n<div id="page_bound">\n\t<a class="bshareDiv" href="http://www.bshare.cn/share">\u5206\u4eab\u6309\u94ae</a><script language="javascript" type="text/javascript" src="http://www.bshare.cn/button.js#uuid=&bp=renren,sinaminiblog,qzone,douban,blog163,blogsina,kaixin001,bgoogle&style=3&fs=4&textcolor=#FFF&bgcolor=#ADADAD&text=\u5206\u4eab\u5230..."></script>\n\t<div class="page_column_left_padding15">\n\t\t<div id="topic_count" align="center" style="background:url(\'/image/global/post_replies.png\') no-repeat scroll 0 0 transparent;width:46px;height:52px;position:absolute;top:-20px;right:-20px;color:#FFFFFF;font-size:18px;padding-left:3px;padding-top:11px;">\n\t\t\t')
# SOURCE LINE 34
__M_writer(filters.decode.utf8(c.topicCount))
__M_writer(u'\n\t\t</div>\n\t\t<div class="top"></div>\n\t\t<div class="content">\n\t\t\t<div id="loc_name" style="clear:both;">\n\t\t\t\t<h1>')
# SOURCE LINE 39
__M_writer(filters.decode.utf8(c.maploc.name))
__M_writer(u'</h1>\n\t\t\t</div>\n\t\t\t')
# SOURCE LINE 41
runtime._include_file(context, u'maploc_module_locinfo.mako', _template_uri)
__M_writer(u'\n\t\t\t<div id="topiclist" style="padding-top:30px;clear:both;"></div>\n\t\t\t<table><tbody>\n\t\t\t\t<tr id="topiclist_example" class="hidden_example">\n\t\t\t\t\t<td id="topic_id" style="display:none;"></td>\n\t\t\t\t\t<td><div id="topic_title"></div></td>\n\t\t\t\t\t<td style="width:100px;"><div id="topic_date" style="text-align:center;color:#A1A0A0;border-left:1px solid #E7E7E7;"></div></td>\n\t\t\t\t\t<td style="width:80px;"><div id="topic_user" style="text-align:center;border-left:1px solid #E7E7E7;"></div></td>\n\t\t\t\t\t<td style="width:30px;"><div id="topic_postcount" style="text-align:center;border-left:1px solid #E7E7E7;"></div></td>\n\t\t\t\t</tr>\n\t\t\t</tbody></table>\n\t\t\t<div id="add_topic" style="width:526px;padding-top:30px;width:100%;clear:both;">\n\t\t\t\t<h2>\u53d1\u8d77\u8bdd\u9898</h2>\n\t\t\t\t<div id="topic_bound" style="padding-top:5px;">\n')
# SOURCE LINE 55
if c.loginUser == None :
# SOURCE LINE 56
__M_writer(u'\t\t\t\t\t\t<div style="padding-left:10px;">\u767b\u5f55\u540e\u521b\u5efa\u8bdd\u9898\u3002</div>\n')
# SOURCE LINE 57
else :
# SOURCE LINE 58
__M_writer(u'\t\t\t\t\t\t<table align="center" style="width:100%;">\n\t\t\t\t\t\t\t<tbody>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td width="30px">\u6807\u9898</td>\n\t\t\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t\t\t<div id="topic_msg" style="float:left;display:none;width:100%;"></div>\n\t\t\t\t\t\t\t\t\t\t<div id="topic_title">\n\t\t\t\t\t\t\t\t\t\t\t<input id="input_title" name="title" maxlength="50" style="width:100%;"></input>\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t\t\t<div id="topic_content" style="">\n\t\t\t\t\t\t\t\t\t\t\t<textarea id="input_content" name="content" style="width:100%;height:70px;"></textarea>\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t\t\t<td><a href="javascript:void(0);" id="button_add_topic"></a></td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t</tbody>\n\t\t\t\t\t\t</table>\n')
pass
# SOURCE LINE 84
__M_writer(u'\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<div style="padding-top:30px;clear:both;"></div>\n\t\t</div>\n\t\t<div class="bottom"></div>\n\t</div>\n\t<div class="page_column_right_padding_left30">\n\t\t<div style="height:20px;clear:both;"></div>\n\t\t<a id="link_return" href="/map"></a>\n\t\t<div style="height:20px;clear:both;"></div>\n')
# SOURCE LINE 94
if c.maploc.store != None :
# SOURCE LINE 95
__M_writer(u'\t\t\t')
runtime._include_file(context, u'maploc_module_discounts.mako', _template_uri)
__M_writer(u'\n\t\t\t<div style="height:30px;clear:both;"></div>\n')
pass
# SOURCE LINE 98
__M_writer(u'\t\t')
runtime._include_file(context, u'maploc_module_gallery.mako', _template_uri)
__M_writer(u'\n\t</div>\n</div>')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1293190519.035128
_template_filename='/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/map/maploc_topic.mako'
_template_uri='map/maploc_topic.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
c = context.get('c', UNDEFINED)
__M_writer = context.writer()
# SOURCE LINE 1
c.jsFiles.append('/script/map/maploc_topic.js?v=12')
# SOURCE LINE 3
__M_writer(u'\n<style type="text/css">\n\t#button_add_post{\n\t\tfloat:right;\n\t\twidth:80px;\n\t\theight:25px;\n\t\tbackground:url(\'/image/global/button_add_post.png\');\n\t}\n\t#button_add_post:hover{background-position:0 -25px;}\n\t#link_return{\n\t\tfloat:left;\n\t\twidth:60px;\n\t\theight:25px;\n\t\tbackground:url(\'/image/global/button_return.png\');\n\t}\n\t#link_return:hover{background-position:0 -25px;}\n</style>\n<div class="page_variable">\n\t<div var_name="info" id="')
# SOURCE LINE 21
__M_writer(filters.decode.utf8(c.topic.id))
__M_writer(u'" maploc_id="')
__M_writer(filters.decode.utf8(c.maploc.id))
__M_writer(u'" name="')
__M_writer(filters.decode.utf8(c.maploc.name))
__M_writer(u'" address="')
__M_writer(filters.decode.utf8(c.maploc.address))
__M_writer(u'"\n\t\ttopic_count="')
# SOURCE LINE 22
__M_writer(filters.decode.utf8(c.topicCount))
__M_writer(u'" rate_count="')
__M_writer(filters.decode.utf8(c.rateCount))
__M_writer(u'" total_rate_score="')
__M_writer(filters.decode.utf8(c.totalRateScore))
__M_writer(u'"\n')
# SOURCE LINE 23
if c.loginUser != None :
# SOURCE LINE 24
__M_writer(u'\t\t\tmy_rating="')
__M_writer(filters.decode.utf8(c.myRating))
__M_writer(u'"\n')
pass
# SOURCE LINE 26
__M_writer(u'\t></div>\n</div>\n<div id="page_bound">\n\t<a class="bshareDiv" href="http://www.bshare.cn/share">\u5206\u4eab\u6309\u94ae</a><script language="javascript" type="text/javascript" src="http://www.bshare.cn/button.js#uuid=&bp=renren,sinaminiblog,qzone,douban,blog163,blogsina,kaixin001,bgoogle&style=3&fs=4&textcolor=#FFF&bgcolor=#ADADAD&text=\u5206\u4eab\u5230..."></script>\n\t<div class="page_column_left_padding15">\n\t\t<div id="topic_count" align="center" style="background:url(\'/image/global/post_replies.png\') no-repeat scroll 0 0 transparent;width:46px;height:52px;position:absolute;top:-20px;right:-20px;color:#FFFFFF;font-size:18px;padding-left:3px;padding-top:11px;">\n\t\t\t')
# SOURCE LINE 32
__M_writer(filters.decode.utf8(c.postCount))
__M_writer(u'\n\t\t</div>\n\t\t<div class="top"></div>\n\t\t<div class="content">\n\t\t\t<h1>')
# SOURCE LINE 36
__M_writer(filters.decode.utf8(c.topic.title))
__M_writer(u'</h1>\n\t\t\t<div id="topic_quote" style="float:left;width:40px;">\n\t\t\t\t<img src="/image/global/sign_quote.gif">\n\t\t\t</div>\n\t\t\t<div id="topic_main" style="float:left;padding-left:10px;width:470px;">\n\t\t\t\t<h3>\n\t\t\t\t\t<span style="float:left;">')
# SOURCE LINE 42
__M_writer(filters.decode.utf8(c.topic.createTime.strftime('%Y-%m-%d %H:%M:%S')))
__M_writer(u'</span>\n\t\t\t\t\t<span style="float:left;padding-left:20px;">')
# SOURCE LINE 43
__M_writer(filters.decode.utf8(c.topic.user.name))
__M_writer(u'</span>\n\t\t\t\t</h3>\n\t\t\t\t<div id="topic_content" style="clear:both;padding-left:10px;">')
# SOURCE LINE 45
__M_writer(filters.decode.utf8(c.topic.content))
__M_writer(u'</div>\n\t\t\t</div>\n\t\t\t<div id="postlist" style="padding-top:30px;clear:both;"></div>\n\t\t\t<div id="postlist_item_example" class="hidden_example">\n\t\t\t\t<div style="border-top:#CCCCCC 1px solid;line-height:14px;clear:both;padding:7px;">\n\t\t\t\t\t<div id="post_content"></div>\n\t\t\t\t\t<div style="color:#999999;padding-top:5px;width:100%;position:relative;">\n\t\t\t\t\t\t<span id="post_date" style="display:inline-block;"></span>\n\t\t\t\t\t\t<span id="post_user" style="padding-left:20px;display:inline-block;"></span>\n\t\t\t\t\t\t<span id="post_user_id" style="display:none;"></span>\n')
# SOURCE LINE 55
if c.loginUser != None :
# SOURCE LINE 56
__M_writer(u'\t\t\t\t\t\t\t<a id="post_reply_link" href="javascript:void(0);" style="position:absolute;right:5px;">\u56de\u590d</a>\n')
pass
# SOURCE LINE 58
__M_writer(u'\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<div id="add_post" style="width:526px;padding-top:30px;width:100%;clear:both;">\n\t\t\t\t<h2>\u53d1\u8d77\u56de\u590d</h2>\n\t\t\t\t<div id="post_bound" style="padding-top:5px;">\n')
# SOURCE LINE 64
if c.loginUser == None :
# SOURCE LINE 65
__M_writer(u'\t\t\t\t\t\t<div style="padding-left:10px;">\u767b\u5f55\u540e\u53d1\u8d77\u56de\u590d\u3002</div>\n')
# SOURCE LINE 66
else :
# SOURCE LINE 67
__M_writer(u'\t\t\t\t\t\t<table align="center" style="width:100%;">\n\t\t\t\t\t\t\t<tbody>\n\t\t\t\t\t\t\t\t<tr><td><div id="post_content" style="">\n\t\t\t\t\t\t\t\t\t<textarea id="input_content" name="content" style="width:100%;height:70px;"></textarea>\n\t\t\t\t\t\t\t\t</div></td></tr>\n\t\t\t\t\t\t\t\t<tr><td><a href="javascript:void(0);" id="button_add_post"></a></td></tr>\n\t\t\t\t\t\t\t</tbody>\n\t\t\t\t\t\t</table>\n')
pass
# SOURCE LINE 76
__M_writer(u'\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<div style="padding-top:30px;clear:both;"></div>\n\t\t</div>\n\t\t<div class="bottom"></div>\n\t</div>\n\t<div class="page_column_right_padding_left30">\n\t\t<div style="height:20px;clear:both;"></div>\n\t\t<a id="link_return" href="/map/maploc?id=')
# SOURCE LINE 84
__M_writer(filters.decode.utf8(c.maploc.id))
__M_writer(u'"></a>\n\t\t<div style="height:10px;clear:both;"></div>\n\t\t')
# SOURCE LINE 86
runtime._include_file(context, u'maploc_module_locinfo.mako', _template_uri)
__M_writer(u'\n')
# SOURCE LINE 87
if c.maploc.store != None :
# SOURCE LINE 88
__M_writer(u'\t\t\t<div style="height:30px;clear:both;"></div>\n\t\t\t')
# SOURCE LINE 89
runtime._include_file(context, u'maploc_module_discounts.mako', _template_uri)
__M_writer(u'\n')
pass
# SOURCE LINE 91
__M_writer(u'\t\t<div style="height:30px;clear:both;"></div>\n\t\t')
# SOURCE LINE 92
runtime._include_file(context, u'maploc_module_gallery.mako', _template_uri)
__M_writer(u'\n\t</div>\n</div>\n \n')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1293295152.02977
_template_filename=u'/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/map/maploc_module_gallery.mako'
_template_uri=u'map/maploc_module_gallery.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
c = context.get('c', UNDEFINED)
__M_writer = context.writer()
# SOURCE LINE 1
c.jsFiles.append('/plugins/jquery_lightbox/js/jquery.lightbox.min.js')
c.cssFiles.append('/plugins/jquery_lightbox/css/jquery.lightbox.min.css')
# SOURCE LINE 4
__M_writer(u'\n<div id="gallery">\n\t<h2>\u56fe\u96c6</h2>\n\t<script type="text/javascript">\n\t\t$(document).ready(function(){\n\t\t\t$("a.gallery_item").lightBox();\n\t\t});\n\t</script>\n')
# SOURCE LINE 12
if c.pics.count() == 0 :
# SOURCE LINE 13
__M_writer(u'\t\t<div style="padding-left:10px;">\u6682\u65e0\u56fe\u7247\u3002</div>\n')
# SOURCE LINE 14
else :
# SOURCE LINE 15
for pic in c.pics :
# SOURCE LINE 16
__M_writer(u'\t\t\t<a class="gallery_item" rel="lightbox[gl]" href="')
__M_writer(filters.decode.utf8(pic.largePic))
__M_writer(u'"><img src="')
__M_writer(filters.decode.utf8(pic.smallPic))
__M_writer(u'" alt="" style="border:1px solid #BBBBBB;margin:7px 5px 7px 0;padding:5px;max-width:160px;"></img></a>\n')
pass
pass
# SOURCE LINE 19
__M_writer(u'</div>')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1292461153.3046739
_template_filename=u'/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/map/maploc_module_discounts.mako'
_template_uri=u'map/maploc_module_discounts.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
c = context.get('c', UNDEFINED)
__M_writer = context.writer()
# SOURCE LINE 1
__M_writer(u'<div id="discounts">\n\t<style type="text/css">\n\t\t#discountlist #list_item:hover{background-color:#F9F9F9;}\n\t</style>\n\t<h2>\u4f18\u60e0</h2>\n')
# SOURCE LINE 6
if c.discounts.count() == 0 :
# SOURCE LINE 7
__M_writer(u'\t\t<div style="padding-left:10px;">\u6682\u65e0\u4f18\u60e0\u3002</div>\n')
# SOURCE LINE 8
else :
# SOURCE LINE 9
__M_writer(u'\t\t<div id="discountlist" style="padding-top:5px;">\n')
# SOURCE LINE 10
for d in c.discounts :
# SOURCE LINE 11
__M_writer(u'\t\t\t<div id="list_item" style="border-bottom:1px solid #DDDDDD;padding:5px;">\n\t\t\t\t<div style="color:#A1A0A0;">')
# SOURCE LINE 12
__M_writer(filters.decode.utf8(d.validTime.strftime('%Y-%m-%d')))
__M_writer(u' -- ')
__M_writer(filters.decode.utf8(d.expireTime.strftime('%Y-%m-%d')))
__M_writer(u'</div>\n\t\t\t\t<div style="padding-left:10px;">')
# SOURCE LINE 13
__M_writer(filters.decode.utf8(d.name))
__M_writer(u'</div>\n\t\t\t</div>\n')
pass
# SOURCE LINE 16
__M_writer(u'\t\t</div>\n')
pass
# SOURCE LINE 18
__M_writer(u'</div>')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1293190626.589577
_template_filename='/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/map/content.mako'
_template_uri='map/content.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
c = context.get('c', UNDEFINED)
__M_writer = context.writer()
# SOURCE LINE 1
import json
c.jsFiles.append('http://maps.google.com/maps/api/js?sensor=false&async=2')
c.jsFiles.append('/script/homepage/homepage.min.js?v=15')
c.cssFiles.append('/css/homepage/content.css?v=10')
__M_locals_builtin_stored = __M_locals_builtin()
__M_locals.update(__M_dict_builtin([(__M_key, __M_locals_builtin_stored[__M_key]) for __M_key in ['json'] if __M_key in __M_locals_builtin_stored]))
# SOURCE LINE 7
__M_writer(u'\r\n<div id="map_service" style="min-height:450px;">\r\n\t<a class="bshareDiv" href="http://www.bshare.cn/share">\u5206\u4eab\u6309\u94ae</a><script language="javascript" type="text/javascript" src="http://www.bshare.cn/button.js#uuid=&bp=renren,sinaminiblog,qzone,douban,blog163,blogsina,kaixin001,bgoogle&style=3&fs=4&textcolor=#FFF&bgcolor=#ADADAD&text=\u5206\u4eab\u5230..."></script>\r\n\t<script type="text/javascript">$(document).ready(function(){if ($.browser.msie && parseInt($.browser.version) <= 7) $(".page_column_right").attr("style", "position:absolute;padding-left:0;");});</script>\r\n\t<div class="page_variable">\r\n\t\t<div var_name="school_maps">')
# SOURCE LINE 12
__M_writer(filters.decode.utf8(json.dumps(c.schoolMaps)))
__M_writer(u'</div>\r\n\t</div>\r\n\t<div id="map_nav" class="tabs" style="width:100%;float:left;"></div>\r\n\t<div style="margin-top:10px;float:left;">\r\n\t\t<div class="page_column_left_nopadding" style="overflow:hidden;z-index:1;">\r\n\t\t\t<ul id="map_locs"></ul>\r\n\t\t</div>\r\n\t\t<div id="map_loc_item_example" class="hidden_example">\r\n\t\t\t<div id="item_bound" style="">\r\n\t\t\t\t<div id="topic_count" align="center"></div>\r\n\t\t\t\t<a id="name"></a>\r\n\t\t\t\t<div id="address"></div>\r\n\t\t\t\t<div id="loc_rating" class="star-rating"></div>\r\n\t\t\t\t<div id="discount_count"></div>\r\n\t\t\t</div>\r\n\t\t</div>\r\n\t\t<div class="page_column_right" style="position:absolute;padding-left:600px;">\r\n\t\t\t<div class="top"></div>\r\n\t\t\t<div class="content" style="height:390px;">\r\n\t\t\t\t<div id="search_bar">\r\n\t\t\t\t\t<span><input id="input_search"></input></span>\r\n\t\t\t\t\t<span id="search_bar_button"></span>\r\n\t\t\t\t</div>\r\n\t\t\t\t<div id="map_canvas" style="width:380px;height:350px;margin:0 10px 0 10px;"></div>\r\n\t\t\t</div>\r\n\t\t\t<div class="bottom"></div>\r\n\t\t</div>\r\n\t</div>\r\n</div>')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1292929586.45962
_template_filename=u'/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/map/maploc_module_locinfo.mako'
_template_uri=u'map/maploc_module_locinfo.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
c = context.get('c', UNDEFINED)
__M_writer = context.writer()
# SOURCE LINE 1
__M_writer(u'<div id="loc_info" style="background:none repeat scroll 0 0 #FFF6ED;padding:10px;">\n\t<script type="text/javascript">\n\t\t$(document).ready(function(){\n\t\t\tvar totalRateScore = parseInt($(".page_variable div[var_name=\'info\']").attr("total_rate_score"));\n\t\t\tvar rateCount = parseInt($(".page_variable div[var_name=\'info\']").attr("rate_count"));\n\t\t\tif (rateCount == 0) $("#rate_score").html("\u6682\u65e0");\n\t\t\telse $("#rate_score").html(Math.round(100.0 * totalRateScore / rateCount) / 100.0 + "\uff08\u6765\u81ea" + rateCount + "\u4f4d\u7528\u6237\uff09");\n')
# SOURCE LINE 8
if c.loginUser != None :
# SOURCE LINE 9
__M_writer(u'\t\t\t\tvar myRating = parseInt($(".page_variable div[var_name=\'info\']").attr("my_rating"));\n\t\t\t\t$("#rater").rater("/map/addSchoolMapLocRating", {curvalue : ')
# SOURCE LINE 10
__M_writer(filters.decode.utf8(c.myRating))
__M_writer(u', getParameter : {id : $(".page_variable div[var_name=\'info\']").attr("maploc_id")}}, updateRating);\n\t\t\t\tfunction updateRating(rating){\n\t\t\t\t\tif (myRating == 0) rateCount ++;\n\t\t\t\t\ttotalRateScore = totalRateScore - myRating + parseInt(rating);\n\t\t\t\t\tmyRating = rating;\n\t\t\t\t\t$("#rate_score").html(Math.round(100.0 * totalRateScore / rateCount) / 100.0 + "\uff08\u6765\u81ea" + rateCount + "\u4f4d\u7528\u6237\uff09");\n\t\t\t\t\t$("#rater").html("");\n\t\t\t\t\t$("#rater").rater("/map/addSchoolMapLocRating", {curvalue : rating, getParameter : {id : $(".page_variable div[var_name=\'info\']").attr("maploc_id")}}, updateRating);\n\t\t\t\t}\n')
pass
# SOURCE LINE 20
__M_writer(u'\t\t});\n\t</script>\n\t<style type="text/css">\n\t\t.table_loc_info .label{width:80px;padding-right:20px;font-weight:bold;color:#E07265;text-align:right;}\n\t</style>\n\t<table class="table_loc_info">\n\t\t<tbody>\n\t\t\t<tr>\n\t\t\t\t<td class="label">\u5730\u5740\uff1a</td>\n\t\t\t\t<td>')
# SOURCE LINE 29
__M_writer(filters.decode.utf8(c.maploc.address))
__M_writer(u'</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td class="label">\u8bc4\u5206\uff1a</td>\n\t\t\t\t<td id="rate_score"></td>\n\t\t\t</tr>\n')
# SOURCE LINE 35
if c.loginUser != None :
# SOURCE LINE 36
__M_writer(u'\t\t\t\t<tr>\n\t\t\t\t\t<td class="label">\u6211\u7684\u8bc4\u5206\uff1a</td>\n\t\t\t\t\t<td><div id="rater"></div></td>\n\t\t\t\t</tr>\n')
pass
# SOURCE LINE 41
__M_writer(u'\t\t </tbody>\n\t</table>\n</div>')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1293294818.023004
_template_filename='/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/manage/extJSFormResult.mako'
_template_uri='manage/extJSFormResult.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
c = context.get('c', UNDEFINED)
__M_writer = context.writer()
# SOURCE LINE 1
__M_writer(u'<html>\n<head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"/></head>\n<body>{success : ')
# SOURCE LINE 3
__M_writer(filters.decode.utf8(c.isSuccess))
__M_writer(u', msg : "')
__M_writer(filters.decode.utf8(c.msg))
__M_writer(u'"}</body>\n</html>\n')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1292532092.8096671
_template_filename='/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/manage/content.mako'
_template_uri='manage/content.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
__M_writer = context.writer()
# SOURCE LINE 1
__M_writer(u'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n<html>\n\t<head>\n\t\t<script type="text/javascript" src="/plugins/ext.JS/adapter/ext/ext-base.js"></script>\n\t\t<script type="text/javascript" src="/plugins/ext.JS/ext-all.js"></script>\n\t\t<script type="text/javascript" src="/plugins/ext.JS/examples/ux/fileuploadfield/FileUploadField.js"></script>\n\t\t<script type="text/javascript" src="/script/manage/App.OperationTree.js"></script>\n\t\t<script type="text/javascript" src="/script/manage/App.UserManagement.Inserting.js"></script>\n\t\t<script type="text/javascript" src="/script/manage/App.UserManagement.CardApplicationViewing.js"></script>\n\t\t<script type="text/javascript" src="/script/manage/App.UserGroupManagement.js"></script>\n\t\t<script type="text/javascript" src="/script/manage/App.MapManagement.SchoolMapLocPicManagement.js"></script>\n\t\t<script type="text/javascript" src="/script/manage/App.MapManagement.DiscountManagement.js"></script>\n\t\t<script type="text/javascript" src="/script/manage/App.139Mail.MessageSending.js"></script>\n\t\t<script type="text/javascript" src="/script/manage/manage.js"></script>\n\t\t<link href="/plugins/ext.JS/examples/ux/fileuploadfield/css/fileuploadfield.css" rel="stylesheet" type="text/css"/>\n\t\t<link href="/css/manage/manage.css" media="screen" rel="stylesheet" type="text/css"/>\n\t\t<link href="/plugins/ext.JS/resources/css/ext-all.css" media="screen" rel="stylesheet" type="text/css"/>\n\t\t<title>Fido - Management</title>\n\t\t<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>\n\t</head>\n\t<body>\n\t\t<div id="header"><div style="background:url(\'/image/global/logo.gif\') repeat scroll 0 0 transparent;height:50px;width:200px;"></div></div>\n\t\t<div id="loading-mask" style=""></div>\n\t\t<div id="loading">\n\t\t\t<div class="loading-indicator"><img src="/image/manage/extanim64.gif" width="64" height="64" style="margin-right:8px;" align="absmiddle"/>Loading...</div>\n\t\t</div>\n\t</body>\n</html>\n')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1293189525.300182
_template_filename='/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/global/global.mako'
_template_uri='global/global.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
c = context.get('c', UNDEFINED)
list = context.get('list', UNDEFINED)
__M_writer = context.writer()
# SOURCE LINE 1
import json
jsFiles = list()
jsFiles.append('/script/global_plugins.merged.min.js?v=14')
jsFiles.append('/script/global/global.merged.min.js?v=16')
jsFiles.extend(c.jsFiles)
c.jsFiles = jsFiles
cssFiles = list()
cssFiles.append('/css/global_plugins.merged.min.css?v=15')
cssFiles.append('/css/global/global.merged.min.css?v=15')
cssFiles.extend(c.cssFiles)
c.cssFiles = cssFiles
__M_locals_builtin_stored = __M_locals_builtin()
__M_locals.update(__M_dict_builtin([(__M_key, __M_locals_builtin_stored[__M_key]) for __M_key in ['cssFiles','json','jsFiles'] if __M_key in __M_locals_builtin_stored]))
# SOURCE LINE 15
__M_writer(u'\n<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n<html>\n\t<head>\n')
# SOURCE LINE 19
for file in c.jsFiles :
# SOURCE LINE 20
__M_writer(u'\t\t<script type="text/javascript" src=')
__M_writer(filters.decode.utf8(file))
__M_writer(u'></script>\n')
pass
# SOURCE LINE 22
for file in c.cssFiles :
# SOURCE LINE 23
__M_writer(u'\t\t<link href="')
__M_writer(filters.decode.utf8(file))
__M_writer(u'" media="screen" rel="stylesheet" type="text/css"/>\n')
pass
# SOURCE LINE 25
__M_writer(u'\t\t<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>\n\t\t<meta name="google-site-verification" content="beG6bNNLUUODWMRbnfUQkioTgS12nnQBQ67G2DUda1U" />\n\t\t<title>')
# SOURCE LINE 27
__M_writer(filters.decode.utf8(c.title))
__M_writer(u'</title>\n\t\t<script type="text/javascript">\n\t\t\tvar _gaq=_gaq||[];_gaq.push([\'_setAccount\',\'UA-20323058-1\']);_gaq.push([\'_trackPageview\']);\n\t\t\t(function(){var ga = document.createElement(\'script\');ga.type=\'text/javascript\';ga.async = true;ga.src=(\'https:\'==document.location.protocol?\'https://ssl\':\'http://www\')+\'.google-analytics.com/ga.js\';\n\t\t\tvar s = document.getElementsByTagName(\'script\')[0];s.parentNode.insertBefore(ga, s);})();\n\t\t</script>\n\t</head>\n\t<body>\n\t\t<div class="page_variable">\n\t\t\t')
# SOURCE LINE 36
l = list()
for s in c.schools : l.append({"id" : s.id, "name" : s.name})
__M_locals_builtin_stored = __M_locals_builtin()
__M_locals.update(__M_dict_builtin([(__M_key, __M_locals_builtin_stored[__M_key]) for __M_key in ['s','l'] if __M_key in __M_locals_builtin_stored]))
# SOURCE LINE 39
__M_writer(u'\n\t\t\t<div var_name="schools">')
# SOURCE LINE 40
__M_writer(filters.decode.utf8(json.dumps(l)))
__M_writer(u'</div>\n\t\t</div>\n\t\t')
# SOURCE LINE 42
__M_writer(filters.decode.utf8(c.header))
__M_writer(u'\n\t\t<div id="globalcontent">')
# SOURCE LINE 43
__M_writer(filters.decode.utf8(c.content))
__M_writer(u'</div>\n\t\t<div style="clear:both;"></div>\n\t\t<div class="global_footer">\n\t\t\t<div class="footer_fido" style="float:left;">ImFido</div>\n\t\t\t<div class="footer_links" style="float:right;">\u5173\u4e8e\u6211\u4eec \xb7 \u9690\u79c1\u58f0\u660e</div>\n\t\t</div>\n\t</body>\n</html>\n')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1293149235.708851
_template_filename='/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/global/globalheader.mako'
_template_uri='global/globalheader.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
c = context.get('c', UNDEFINED)
url = context.get('url', UNDEFINED)
request = context.get('request', UNDEFINED)
len = context.get('len', UNDEFINED)
range = context.get('range', UNDEFINED)
str = context.get('str', UNDEFINED)
__M_writer = context.writer()
# SOURCE LINE 1
curSchoolId = 0
tmpId = -1
if request.cookies.has_key('global.school.id') : tmpId = request.cookies['global.school.id']
for i in range(0, len(c.schools)) :
s = c.schools[i]
if tmpId == str(s.id) : curSchoolId = i
__M_locals_builtin_stored = __M_locals_builtin()
__M_locals.update(__M_dict_builtin([(__M_key, __M_locals_builtin_stored[__M_key]) for __M_key in ['i','tmpId','curSchoolId','s'] if __M_key in __M_locals_builtin_stored]))
# SOURCE LINE 8
__M_writer(u'\r\n<div class="global_header"><div id="global_header_mid">\r\n\t<script type="text/javascript">\r\n\t\t$(document).ready(function(){\r\n\t\t\tvar schoolMenu = $("#global_panel #school_menu");\r\n\t\t\tvar loginMenu = $("#global_panel #login_menu");\r\n\t\t\tvar notifyMenu = $("#global_panel #notification_menu");\r\n\t\t\t$("#global_panel #school").click(function(){\r\n\t\t\t\tschoolMenu.removeClass("menu");\r\n\t\t\t\tschoolMenu.addClass("menu_show");\r\n\t\t\t\tschoolMenu.css("left", $("#global_panel #school").width() - schoolMenu.width() + 8 + "px");\r\n\t\t\t\t$("#global_panel #school").removeClass("head_normal");\r\n\t\t\t\t$("#global_panel #school").addClass("head_activated");\r\n\t\t\t});\r\n\t\t\t$("#global_panel #login").click(function(){\r\n\t\t\t\tloginMenu.removeClass("menu");\r\n\t\t\t\tloginMenu.addClass("menu_show");\r\n\t\t\t\tloginMenu.css("left", $("#global_panel #login").width() - loginMenu.width() + 8 + "px");\r\n\t\t\t\t$("#global_panel #login").removeClass("head_normal");\r\n\t\t\t\t$("#global_panel #login").addClass("head_activated");\r\n\t\t\t});\r\n\t\t\t$("#global_panel #notification").click(function(){\r\n\t\t\t\tnotifyMenu.removeClass("menu");\r\n\t\t\t\tnotifyMenu.addClass("menu_show");\r\n\t\t\t\tnotifyMenu.css("left", $("#global_panel #notification").width() - notifyMenu.width() + 8 + "px");\r\n\t\t\t\t$("#global_panel #notification").removeClass("head_normal");\r\n\t\t\t\t$("#global_panel #notification").addClass("head_activated");\r\n\t\t\t});\r\n\t\t\t$(document).click(function(event){\r\n\t\t\t\tif (!$(event.target).closest("#global_panel #school_menu").size() && !$(event.target).closest("#global_panel #school").size()){\r\n\t\t\t\t\tschoolMenu.addClass("menu");\r\n\t\t\t\t\tschoolMenu.removeClass("menu_show");\r\n\t\t\t\t\t$("#global_panel #school").addClass("head_normal");\r\n\t\t\t\t\t$("#global_panel #school").removeClass("head_activated");\r\n\t\t\t\t}\r\n\t\t\t\tif (!$(event.target).closest("#global_panel #login_menu").size() && !$(event.target).closest("#global_panel #login").size()){\r\n\t\t\t\t\tloginMenu.addClass("menu");\r\n\t\t\t\t\tloginMenu.removeClass("menu_show");\r\n\t\t\t\t\t$("#global_panel #login").addClass("head_normal");\r\n\t\t\t\t\t$("#global_panel #login").removeClass("head_activated");\r\n\t\t\t\t}\r\n\t\t\t\tif (!$(event.target).closest("#global_panel #notification_menu").size() && !$(event.target).closest("#global_panel #notification").size()){\r\n\t\t\t\t\tnotifyMenu.addClass("menu");\r\n\t\t\t\t\tnotifyMenu.removeClass("menu_show");\r\n\t\t\t\t\t$("#global_panel #notification").addClass("head_normal");\r\n\t\t\t\t\t$("#global_panel #notification").removeClass("head_activated");\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t});\r\n\t</script>\r\n\t<div id="fidologo"><a href="/map"></a></div>\r\n\t<div id="globalnav">\r\n')
# SOURCE LINE 60
if url.current()[ : 4] == '/map' or url.current()[ : 18] == '/dispatch.fcgi/map':
# SOURCE LINE 61
__M_writer(u'\t\t<li><a id="link_places_cur"></a></li>\r\n')
# SOURCE LINE 62
else :
# SOURCE LINE 63
__M_writer(u'\t\t<li><a id="link_places" href="/map"></a></li>\r\n')
pass
# SOURCE LINE 65
if url.current()[ : 6] == '/login' or url.current()[ : 20] == '/dispatch.fcgi/login':
# SOURCE LINE 66
__M_writer(u'\t\t\t<li><a id="link_myfido_cur"></a></li>\r\n')
# SOURCE LINE 67
else :
# SOURCE LINE 68
__M_writer(u'\t\t\t<li><a id="link_myfido" href="/login"></a></li>\r\n')
pass
# SOURCE LINE 70
__M_writer(u'\t</div>\r\n\t<div id="globalpanel">\r\n\t\t<div id="global_panel">\r\n\t\t\t<div style="float:left;position:relative;">\r\n\t\t\t\t<div id="school_menu" class="menu">\r\n\t\t\t\t\t<h2>\u8bf7\u9009\u62e9\u5b66\u6821...</h2>\r\n\t\t\t\t\t<div style="border-bottom:1px solid #CCCCCC;margin:3px 0;"></div>\r\n\t\t\t\t\t<ul>\r\n')
# SOURCE LINE 78
for s in c.schools :
# SOURCE LINE 79
__M_writer(u'\t\t\t\t\t\t\t<li><a href="javascript:globalCtrl.setCurSchool(')
__M_writer(filters.decode.utf8(s.id))
__M_writer(u');">')
__M_writer(filters.decode.utf8(s.name))
__M_writer(u'</a></li>\r\n')
pass
# SOURCE LINE 81
__M_writer(u'\t\t\t\t\t</ul>\r\n\t\t\t\t</div>\r\n\t\t\t\t<div id="school" class="head_normal">\r\n\t\t\t\t\t<span id="school_icon"></span>\r\n\t\t\t\t\t<span id="cur_school">')
# SOURCE LINE 85
__M_writer(filters.decode.utf8(c.schools[curSchoolId].name))
__M_writer(u'</span>\r\n\t\t\t\t\t<span id="global_menu_dropdown"></span>\r\n\t\t\t\t</div>\r\n\t\t\t</div>\r\n')
# SOURCE LINE 89
if c.loginUser != None :
# SOURCE LINE 90
__M_writer(u'\t\t\t\t<div style="float:left;position:relative;">\r\n\t\t\t\t\t<div id="notification_menu" class="menu">\r\n\t\t\t\t\t\t<h2>\u6d88\u606f</h2>\r\n\t\t\t\t\t\t<div style="border-bottom:1px solid #CCCCCC;margin:3px 0;"></div>\r\n\t\t\t\t\t\t<ul>\r\n\t\t\t\t\t\t\t')
# SOURCE LINE 95
notifyCount = 0
__M_locals_builtin_stored = __M_locals_builtin()
__M_locals.update(__M_dict_builtin([(__M_key, __M_locals_builtin_stored[__M_key]) for __M_key in ['notifyCount'] if __M_key in __M_locals_builtin_stored]))
# SOURCE LINE 97
__M_writer(u'\r\n')
# SOURCE LINE 98
for n in c.loginUser.notifications :
# SOURCE LINE 99
__M_writer(u'\t\t\t\t\t\t\t\t')
notifyCount += 1
__M_locals_builtin_stored = __M_locals_builtin()
__M_locals.update(__M_dict_builtin([(__M_key, __M_locals_builtin_stored[__M_key]) for __M_key in ['notifyCount'] if __M_key in __M_locals_builtin_stored]))
__M_writer(u'\r\n\t\t\t\t\t\t\t\t<li><div id="update_time">')
# SOURCE LINE 100
__M_writer(filters.decode.utf8(n.updateTime.strftime('%m-%d %H:%M')))
__M_writer(u'</div><div id="content">')
__M_writer(filters.decode.utf8(n.content))
__M_writer(u'</div></li>\r\n')
pass
# SOURCE LINE 102
if notifyCount == 0 :
# SOURCE LINE 103
__M_writer(u'\t\t\t\t\t\t\t\t\u6682\u65e0\u65b0\u6d88\u606f\r\n')
pass
# SOURCE LINE 105
__M_writer(u'\t\t\t\t\t\t</ul>\r\n\t\t\t\t\t</div>\r\n\t\t\t\t\t<div id="notification" class="head_normal">\r\n\t\t\t\t\t\t<span id="head">\t\r\n\t\t\t\t\t\t\t<span id="notification_icon"></span>\r\n\t\t\t\t\t\t\t<span id="notification_count">')
# SOURCE LINE 110
__M_writer(filters.decode.utf8(notifyCount))
__M_writer(u'\u6761\u6d88\u606f</span>\r\n\t\t\t\t\t\t\t<span id="global_menu_dropdown"></span>\r\n\t\t\t\t\t\t</span>\r\n\t\t\t\t\t</div>\r\n\t\t\t\t</div>\r\n\t\t\t\t<div style="float:left;position:relative;">\r\n\t\t\t\t\t<div id="login_menu" class="menu">\r\n\t\t\t\t\t\t<div style="clear:both;"><a href="/login/index/settings">\u8bbe\u7f6e</a></div>\r\n\t\t\t\t\t\t<div style="clear:both;"><a href="javascript:globalCtrl.logout();">\u767b\u51fa</a></div>\r\n\t\t\t\t\t</div>\r\n\t\t\t\t\t<div id="login" class="head_normal">\r\n\t\t\t\t\t\t<span id="head">\t\r\n\t\t\t\t\t\t\t<span id="user_icon"></span>\r\n\t\t\t\t\t\t\t<span id="global_menu_user_name">')
# SOURCE LINE 123
__M_writer(filters.decode.utf8(c.loginUser.name))
__M_writer(u'</span>\r\n\t\t\t\t\t\t\t<span id="global_menu_dropdown"></span>\r\n\t\t\t\t\t\t</span>\r\n\t\t\t\t\t</div>\r\n\t\t\t\t</div>\r\n')
# SOURCE LINE 128
else :
# SOURCE LINE 129
__M_writer(u'\t\t\t\t<div id="dv_login"><span id="login_icon"></span><a href="/login">\u767b\u5f55</a></div>\r\n\t\t\t\t<div id="dv_signup"><span id="signup_icon"></span><a href="/login/signup">\u6ce8\u518c</a></div>\r\n')
pass
# SOURCE LINE 132
__M_writer(u'\t\t</div>\r\n</div></div>\r\n\r\n')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1292947239.955646
_template_filename='/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/homepage/content.mako'
_template_uri='homepage/content.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
c = context.get('c', UNDEFINED)
list = context.get('list', UNDEFINED)
__M_writer = context.writer()
# SOURCE LINE 1
cssFiles = list()
cssFiles.append('/css/global/global.css?v=11')
cssFiles.extend(c.cssFiles)
c.cssFiles = cssFiles
__M_locals_builtin_stored = __M_locals_builtin()
__M_locals.update(__M_dict_builtin([(__M_key, __M_locals_builtin_stored[__M_key]) for __M_key in ['cssFiles'] if __M_key in __M_locals_builtin_stored]))
# SOURCE LINE 6
__M_writer(u'\r\n<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\r\n<html>\r\n\t<head>\r\n')
# SOURCE LINE 10
for file in c.jsFiles :
# SOURCE LINE 11
__M_writer(u'\t\t<script type="text/javascript" src=')
__M_writer(filters.decode.utf8(file))
__M_writer(u'></script>\r\n')
pass
# SOURCE LINE 13
for file in c.cssFiles :
# SOURCE LINE 14
__M_writer(u'\t\t<link href="')
__M_writer(filters.decode.utf8(file))
__M_writer(u'" media="screen" rel="stylesheet" type="text/css"/>\r\n')
pass
# SOURCE LINE 16
__M_writer(u'\t\t<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>\r\n\t\t<meta name="google-site-verification" content="beG6bNNLUUODWMRbnfUQkioTgS12nnQBQ67G2DUda1U" />\r\n\t\t<title>')
# SOURCE LINE 18
__M_writer(filters.decode.utf8(c.title))
__M_writer(u'</title>\r\n\t</head>\r\n\t<body>\r\n\t\t<style type="text/css">\r\n\t\t\t#globalcontent #fidologo{\r\n\t\t\t\tfloat:left;\r\n\t\t\t\tmargin-top:10px;\r\n\t\t\t\tmargin-bottom:30px;\r\n\t\t\t\theight:50px;\r\n\t\t\t\twidth:200px;\r\n\t\t\t\tbackground:url(\'/image/global/logo.gif\');\r\n\t\t\t}\r\n\t\t\t#globalcontent #button_login{\r\n\t\t\t\tfloat:left;\r\n\t\t\t\twidth:130px;\r\n\t\t\t\theight:45px;\r\n\t\t\t\tbackground:url(\'/image/global/button_login.png\');\r\n\t\t\t}\r\n\t\t\t#globalcontent #button_login:hover{background-position:0 -45px;}\r\n\t\t\t#globalcontent #button_login{\r\n\t\t\t\tfloat:left;\r\n\t\t\t\twidth:130px;\r\n\t\t\t\theight:45px;\r\n\t\t\t\tbackground:url(\'/image/global/button_login.png\');\r\n\t\t\t}\r\n\t\t\t#globalcontent #button_login:hover{background-position:0 -45px;}\r\n\t\t\t#globalcontent #button_signup{\r\n\t\t\t\tfloat:left;\r\n\t\t\t\twidth:130px;\r\n\t\t\t\theight:45px;\r\n\t\t\t\tbackground:url(\'/image/global/button_signup.png\');\r\n\t\t\t}\r\n\t\t\t#globalcontent #button_signup:hover{background-position:0 -45px;}\r\n\t\t\t#globalcontent #button_enter{\r\n\t\t\t\tfloat:left;\r\n\t\t\t\twidth:60px;\r\n\t\t\t\theight:30px;\r\n\t\t\t\tbackground:url(\'/image/global/button_enter.png\');\r\n\t\t\t}\r\n\t\t\t#globalcontent #button_enter:hover{background-position:0 -30px;}\r\n\t\t</style>\r\n\t\t<div id="globalcontent">\r\n\t\t\t<div style="width:100%;">\r\n\t\t\t\t<div id="fidologo"></div>\r\n\t\t\t</div>\r\n\t\t\t<div style="clear:both;"></div>\r\n\t\t\t<div>\r\n\t\t\t\t<div style="float:left;width:560px;height:430px;background:url(\'/image/homepage/homepage_banner.png\')">\r\n\t\t\t\t\t<a href="/map" id="button_enter" style="margin:215px 0 0 495px;"></a>\r\n\t\t\t\t</div>\r\n\t\t\t\t<div style="float:left;margin-left:80px;width:310px;height:464px;background:url(\'/image/homepage/homepage_right_column.png\')">\r\n\t\t\t\t\t<a href="/login" id="button_login" style="margin:60px 0 0 150px;"></a>\r\n\t\t\t\t\t<a href="/login/signup" id="button_signup" style="margin:280px 0 0 150px;"></a>\r\n\t\t\t\t</div>\r\n\t\t\t</div>\r\n\t\t</div>\r\n\t\t<div style="clear:both;"></div>\r\n\t\t<div class="global_footer">\r\n\t\t\t<div class="footer_fido" style="float:left;">ImFido</div>\r\n\t\t\t<div class="footer_links" style="float:right;">\u5173\u4e8e\u6211\u4eec \xb7 \u9690\u79c1\u58f0\u660e</div>\r\n\t\t</div>\r\n\t</body>\r\n</html>')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1292685833.045639
_template_filename='/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/login/forgetpassword.mako'
_template_uri='login/forgetpassword.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
c = context.get('c', UNDEFINED)
__M_writer = context.writer()
# SOURCE LINE 1
c.cssFiles.append('/css/login/login.css')
# SOURCE LINE 3
__M_writer(u'\n<script type="text/javascript">\nfunction validateMobile(){\n\tvar mobile = $("#form_forgetpassword #fg_input_mobile").val();\n\tif (!isValidMobile(mobile)) return false;\n\treturn true;\n}\n$(document).ready(function(){\n\t$("#form_forgetpassword").validationEngine();\n\t$("#button_continue").click(function(){\n\t\t$.validationEngine.submitValidation("#form_forgetpassword"); \n\t\tvar obj = this;\n\t\tvar mobile = $("#form_forgetpassword #fg_input_mobile").val();\n\t\tif (!isValidMobile(mobile)) return;\n\t\t$.validationEngine.buildPrompt("#form_forgetpassword #button_continue", "\u6b63\u5728\u63d0\u4ea4\u8bf7\u6c42\uff0c\u8bf7\u7a0d\u5019\u3002", "load");\n\t\t$.get("/login/resetPassword", {mobile : mobile}, function(data){\n\t\t\tif (data == "too fast"){\n\t\t\t\t$.validationEngine.closePrompt("#form_forgetpassword #button_continue");\n\t\t\t\t$.validationEngine.buildPrompt("#form_forgetpassword #button_continue", "\u60a8\u7684\u63d0\u4ea4\u8fc7\u4e8e\u9891\u7e41\uff0c\u8bf7\u7a0d\u5019\u5c1d\u8bd5\u3002", "error");\n\t\t\t} else if (data == "unregistered user"){\n\t\t\t\t$.validationEngine.closePrompt("#form_forgetpassword #button_continue");\n\t\t\t\t$.validationEngine.buildPrompt("#form_forgetpassword #login_input_mobile", "\u60a8\u8f93\u5165\u7684\u624b\u673a\u53f7\u672a\u5728\u672c\u7f51\u7ad9\u6ce8\u518c\uff0c\u8bf7\u91cd\u65b0\u8f93\u5165\u3002", "error");\n\t\t\t} else if (data == "success"){\n\t\t\t\t$.validationEngine.buildPrompt("#form_forgetpassword #button_continue", "\u60a8\u7684\u5bc6\u7801\u5df2\u91cd\u7f6e\uff0c\u8bf7\u68c0\u67e5\u60a8\u7684139\u90ae\u7bb1\u3002", "pass");\n\t\t\t\tsetTimeout("window.location = \'/login\';", 2000);\n\t\t\t} else {\n\t\t\t\t$.validationEngine.closePrompt("#form_forgetpassword #button_continue");\n\t\t\t\t$.validationEngine.buildPrompt("#form_forgetpassword #button_continue", "\u8bf7\u6c42\u5931\u8d25\u3002", "error");\n\t\t\t} \n\t\t});\n\t});\n});\n</script>\n<div id="login_bound">\n\t<h1>\u5bc6\u7801\u627e\u56de</h1>\n\t<div class="page_column_left_padding15">\n\t\t<div class="top"></div>\n\t\t<div class="content">\n\t\t\t<form id="form_forgetpassword">\n\t\t\t\t<div id="fg_mobile">\n\t\t\t\t\t<label>\u624b\u673a\u53f7</label>\n\t\t\t\t\t<input id="fg_input_mobile" type="text" name="mobile" class="validate[required,funcCall[validateMobile]]"></input>\n\t\t\t\t</div>\n\t\t\t\t<div id="bottom_buttons" style="clear:both;">\n\t\t\t\t\t<div id="button_continue" style="cursor:pointer;float:right;width:140px;height:35px;background:url(\'/image/global/continue_button.gif\') no-repeat scroll 0 0 transparent;"></div>\n\t\t\t\t</div>\n\t\t\t</form>\n\t\t</div>\n\t\t<div class="bottom"></div>\n\t</div>\n\t<div class="page_column_right_padding_left30">\n\t\t<h2>\u5982\u4f55\u624d\u80fd\u627e\u56de\u6211\u7684\u5bc6\u7801\uff1f</h2>\n\t\t<p>\u4e3a\u4e86\u60a8\u7684\u5b89\u5168\uff0c\u60a8\u7684\u5bc6\u7801\u4e0d\u4f1a\u4ee5\u660e\u6587\u7684\u5f62\u5f0f\u5728\u670d\u52a1\u5668\u4e0a\u4fdd\u5b58\uff0c\u56e0\u6b64\uff0c\u5728\u60a8\u9009\u62e9\u201c\u627e\u56de\u5bc6\u7801\u201d\u540e\uff0c\u6211\u4eec\u5c06<strong>\u91cd\u7f6e</strong>\u60a8\u7684\u5bc6\u7801\uff0c\u5e76\u5c06\u91cd\u7f6e\u540e\u7684\u5bc6\u7801\u53d1\u9001\u81f3\u60a8\u7684139\u90ae\u7bb1\u3002</p>\n\t\t<p>\u60a8\u53ea\u9700\u8981\u586b\u5165\u60a8\u7684\u624b\u673a\u53f7\u5373\u53ef\u91cd\u7f6e\u5bc6\u7801\u3002</p>\n\t\t<p>\u5728\u83b7\u53d6\u91cd\u7f6e\u540e\u7684\u5bc6\u7801\u540e\uff0c<strong>\u8bf7\u60a8\u53ca\u65f6\u4fee\u6539\u5bc6\u7801</strong>\u3002\u60a8\u53ef\u4ee5\u5728\u60a8\u7684\u4e2a\u4eba\u8bbe\u7f6e\u9875\u9762\u4fee\u6539\u60a8\u7684\u5bc6\u7801\u3002</p>\n\t</div>\n</div>\n')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1292939922.820404
_template_filename='/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/login/signup.mako'
_template_uri='login/signup.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
c = context.get('c', UNDEFINED)
request = context.get('request', UNDEFINED)
__M_writer = context.writer()
# SOURCE LINE 1
c.jsFiles.append('/script/login/signup.js?v=12')
# SOURCE LINE 3
__M_writer(u'\n<style type="text/css">\n#require_code{\n\tcursor:pointer;\n\tposition:absolute;\n\tright:0;\n\twidth:90px;\n\theight:25px;\n\tmargin-right:120px;\n\tbackground:url(\'/image/global/button_send_authcode.png\');\n}\n#require_code:hover{background-position:0 -25px;}\n#form_signup #submit{\n\tcursor:pointer;\n\tposition:absolute;\n\tright:30px;\n\twidth:130px;\n\theight:25px;\n\tbackground:url(\'/image/global/button_ensure_signup.png\');\n}\n#form_signup #submit:hover{background-position:0 -25px;}\n</style>\n<div id="signup_page_bound">\n\t<div class="page_variable">\n\t\t<div var_name="errMsg">')
# SOURCE LINE 27
__M_writer(filters.decode.utf8(c.errMsg))
__M_writer(u'</div>\n\t\t<div var_name="last_signup_gender">\n')
# SOURCE LINE 29
if 'gender' in request.POST :
# SOURCE LINE 30
__M_writer(u'\t\t\t\t')
__M_writer(filters.decode.utf8(request.POST['gender']))
__M_writer(u'\n')
pass
# SOURCE LINE 32
__M_writer(u'\t\t</div>\n\t\t<div var_name="last_signup_birthday_year">\n')
# SOURCE LINE 34
if 'birthday_year' in request.POST :
# SOURCE LINE 35
__M_writer(u'\t\t\t\t')
__M_writer(filters.decode.utf8(request.POST['birthday_year']))
__M_writer(u'\n')
pass
# SOURCE LINE 37
__M_writer(u'\t\t</div>\n\t\t<div var_name="last_signup_birthday_month">\n')
# SOURCE LINE 39
if 'birthday_month' in request.POST :
# SOURCE LINE 40
__M_writer(u'\t\t\t\t')
__M_writer(filters.decode.utf8(request.POST['birthday_month']))
__M_writer(u'\n')
pass
# SOURCE LINE 42
__M_writer(u'\t\t</div>\n\t\t<div var_name="last_signup_birthday_day">\n')
# SOURCE LINE 44
if 'birthday_day' in request.POST :
# SOURCE LINE 45
__M_writer(u'\t\t\t\t')
__M_writer(filters.decode.utf8(request.POST['birthday_day']))
__M_writer(u'\n')
pass
# SOURCE LINE 47
__M_writer(u'\t\t</div>\n\t\t<div var_name="last_signup_school">\n')
# SOURCE LINE 49
if 'school' in request.POST :
# SOURCE LINE 50
__M_writer(u'\t\t\t\t')
__M_writer(filters.decode.utf8(request.POST['school']))
__M_writer(u'\n')
pass
# SOURCE LINE 52
__M_writer(u'\t\t</div>\n\t\t<div var_name="last_signup_profession">\n')
# SOURCE LINE 54
if 'profession' in request.POST :
# SOURCE LINE 55
__M_writer(u'\t\t\t\t')
__M_writer(filters.decode.utf8(request.POST['profession']))
__M_writer(u'\n')
pass
# SOURCE LINE 57
__M_writer(u'\t\t</div>\n\t\t<div var_name="last_signup_grade">\n')
# SOURCE LINE 59
if 'grade' in request.POST :
# SOURCE LINE 60
__M_writer(u'\t\t\t\t')
__M_writer(filters.decode.utf8(request.POST['grade']))
__M_writer(u'\n')
pass
# SOURCE LINE 62
__M_writer(u'\t\t</div>\n\t</div>\n')
# SOURCE LINE 64
if 'method' in request.GET and request.GET['method'] == 'email' :
# SOURCE LINE 65
__M_writer(u'\t\t<h1>\u90ae\u7bb1\u6ce8\u518c<span style="font-weight:normal;font-size:12px;">\uff08<a href="/login/signup">\u624b\u673a\u6ce8\u518c\uff1f</a>\uff09</span></h1>\n')
# SOURCE LINE 66
else :
# SOURCE LINE 67
__M_writer(u'\t\t<h1>\u624b\u673a\u6ce8\u518c<span style="font-weight:normal;font-size:12px;">\uff08<a href="/login/signup?method=email">\u90ae\u7bb1\u6ce8\u518c\uff1f</a>\uff09</span></h1>\n')
pass
# SOURCE LINE 69
__M_writer(u'\t<div class="page_column_left_padding15">\n\t\t<div class="top"></div>\n\t\t<div class="content">\n')
# SOURCE LINE 72
if 'method' in request.GET and request.GET['method'] == 'email' :
# SOURCE LINE 73
__M_writer(u'\t\t\t<form id="form_signup" method="post" action="/login/signup?method=email" onsubmit="return checkForm();">\n')
# SOURCE LINE 74
else :
# SOURCE LINE 75
__M_writer(u'\t\t\t<form id="form_signup" method="post" action="/login/signup" onsubmit="return checkForm();">\n')
pass
# SOURCE LINE 77
__M_writer(u'\t\t\t\t<h2>\u5b9e\u540d\u4fe1\u606f</h2>\n')
# SOURCE LINE 78
if 'method' in request.GET and request.GET['method'] == 'email' :
# SOURCE LINE 79
__M_writer(u'\t\t\t\t\t<div id="signup_email">\n\t\t\t\t\t\t<label>\u90ae\u7bb1</label>\n')
# SOURCE LINE 81
if 'email' in request.POST :
# SOURCE LINE 82
__M_writer(u'\t\t\t\t\t\t\t<input type="input" id="signup_input_email" name="email" class="validate[required,custom[email]]" value="')
__M_writer(filters.decode.utf8(request.POST['email']))
__M_writer(u'"></input>\n')
# SOURCE LINE 83
else :
# SOURCE LINE 84
__M_writer(u'\t\t\t\t\t\t\t<input type="input" id="signup_input_email" name="email" class="validate[required,custom[email]]" value=""></input>\n')
pass
# SOURCE LINE 86
__M_writer(u'\t\t\t\t\t\t<a href="javascript:void(0);" id="require_code"></a>\n\t\t\t\t\t</div>\n')
# SOURCE LINE 88
else :
# SOURCE LINE 89
__M_writer(u'\t\t\t\t\t<div id="signup_mobile">\n\t\t\t\t\t\t<label>\u624b\u673a\u53f7</label>\n')
# SOURCE LINE 91
if 'mobile' in request.POST :
# SOURCE LINE 92
__M_writer(u'\t\t\t\t\t\t\t<input id="signup_input_mobile" name="mobile" class="validate[required,funcCall[validateMobile]]" value="')
__M_writer(filters.decode.utf8(request.POST['mobile']))
__M_writer(u'"></input>\n')
# SOURCE LINE 93
else :
# SOURCE LINE 94
__M_writer(u'\t\t\t\t\t\t\t<input id="signup_input_mobile" name="mobile" class="validate[required,funcCall[validateMobile]]" value=""></input>\n')
pass
# SOURCE LINE 96
__M_writer(u'\t\t\t\t\t\t<a href="javascript:void(0);" id="require_code"></a>\n\t\t\t\t\t</div>\n')
pass
# SOURCE LINE 99
__M_writer(u'\t\t\t\t<div id="signup_register_code">\n\t\t\t\t\t<label>\u9a8c\u8bc1\u7801</label>\n')
# SOURCE LINE 101
if 'registerCode' in request.POST :
# SOURCE LINE 102
__M_writer(u'\t\t\t\t\t\t<input id="input_register_code" name="registerCode" class="validate[required,fixedLength[8]]" value="')
__M_writer(filters.decode.utf8(request.POST['registerCode']))
__M_writer(u'"></input>\n')
# SOURCE LINE 103
else :
# SOURCE LINE 104
__M_writer(u'\t\t\t\t\t\t<input id="input_register_code" name="registerCode" class="validate[required,fixedLength[8]]" value=""></input>\n')
pass
# SOURCE LINE 106
__M_writer(u'\t\t\t\t</div>\n\t\t\t\t<div id="signup_password">\n\t\t\t\t\t<label>\u5bc6\u7801</label>\n\t\t\t\t\t<input type="password" name="password" id="input_password" class="validate[required,funcCall[validateNewPass]]"></input>\n\t\t\t\t</div>\n\t\t\t\t<div id="signup_confirm_pass">\n\t\t\t\t\t<label>\u786e\u8ba4\u5bc6\u7801</label>\n\t\t\t\t\t<input type="password" id="input_confirm_pass" class="validate[required,funcCall[validateRetypePass]]"></input>\n\t\t\t\t</div>\n\t\t\t\t<h2>\u57fa\u672c\u4fe1\u606f</h2>\n\t\t\t\t<div id="signup_name">\n\t\t\t\t\t<label>\u59d3\u540d</label>\n')
# SOURCE LINE 118
if 'name' in request.POST :
# SOURCE LINE 119
__M_writer(u'\t\t\t\t\t\t<input id="input_name" name="name" class="validate[required,uLength[4,16],funcCall[validateName]]" value="')
__M_writer(filters.decode.utf8(request.POST['name']))
__M_writer(u'"></input>\n')
# SOURCE LINE 120
else :
# SOURCE LINE 121
__M_writer(u'\t\t\t\t\t\t<input id="input_name" name="name" class="validate[required,uLength[4,16],funcCall[validateName]]" value=""></input>\n')
pass
# SOURCE LINE 123
__M_writer(u'\t\t\t\t</div>\n\t\t\t\t<div id="signup_gender">\n\t\t\t\t\t<label>\u6027\u522b</label>\n\t\t\t\t\t<input type="radio" name="gender" id="input_gender" class="validate[required]" value="male">\u7537</input>\n\t\t\t\t\t<input type="radio" name="gender" id="input_gender" class="validate[required]" value="female">\u5973</input>\n\t\t\t\t</div>\n\t\t\t\t<div id="signup_birthday">\n\t\t\t\t\t<label>\u751f\u65e5</label>\n\t\t\t\t\t<select name="birthday_year" id="input_birthday_year" style="width:70px;">\n\t\t\t\t\t\t<option value=\'--\'>\u8bf7\u9009\u62e9</option>\n\t\t\t\t\t</select>\n\t\t\t\t\t<select name="birthday_month" id="input_birthday_month" style="width:42px;">\n\t\t\t\t\t\t<option value=\'--\'>--</option>\n\t\t\t\t\t</select>\n\t\t\t\t\t<select name="birthday_day" id="input_birthday_day" style="width:42px;">\n\t\t\t\t\t\t<option value=\'--\'>--</option>\n\t\t\t\t\t</select>\n\t\t\t\t</div>\n\t\t\t\t<div id="signup_school">\n\t\t\t\t\t<label>\u5b66\u6821</label>\n\t\t\t\t\t<select name="school" id="input_school" style="width:160px;"></select>\n\t\t\t\t</div>\n\t\t\t\t<div id="signup_profession">\n\t\t\t\t\t<label>\u4e13\u4e1a</label>\n\t\t\t\t\t<select name="profession" id="input_profession" style="width:160px;">\n\t\t\t\t\t</select>\n\t\t\t\t</div>\n\t\t\t\t<div id="user_grade">\n\t\t\t\t\t<label>\u5e74\u7ea7</label>\n\t\t\t\t\t<select name="grade" id="input_grade" style="width:160px;">\n\t\t\t\t\t\t<option value=\'--\'>\u8bf7\u9009\u62e9</option>\n\t\t\t\t\t</select>\n\t\t\t\t</div>\n\t\t\t\t<h2>\u9644\u52a0\u4fe1\u606f</h2>\n')
# SOURCE LINE 157
if 'method' in request.GET and request.GET['method'] == 'email' :
# SOURCE LINE 158
__M_writer(u'\t\t\t\t\t<div id="signup_mobile">\n\t\t\t\t\t\t<label>\u624b\u673a\u53f7</label>\n')
# SOURCE LINE 160
if 'mobile' in request.POST :
# SOURCE LINE 161
__M_writer(u'\t\t\t\t\t\t\t<input id="signup_input_mobile" name="mobile" class="validate[optional,funcCall[validateMobile]]" value="')
__M_writer(filters.decode.utf8(request.POST['mobile']))
__M_writer(u'"></input>\n')
# SOURCE LINE 162
else :
# SOURCE LINE 163
__M_writer(u'\t\t\t\t\t\t\t<input id="signup_input_mobile" name="mobile" class="validate[optional,funcCall[validateMobile]]" value=""></input>\n')
pass
# SOURCE LINE 165
__M_writer(u'\t\t\t\t\t</div>\n')
# SOURCE LINE 166
else :
# SOURCE LINE 167
__M_writer(u'\t\t\t\t\t<div id="signup_email">\n\t\t\t\t\t\t<label>\u5e38\u7528\u90ae\u7bb1</label>\n')
# SOURCE LINE 169
if 'email' in request.POST :
# SOURCE LINE 170
__M_writer(u'\t\t\t\t\t\t\t<input type="input" id="signup_input_email" name="email" class="validate[optional,custom[email]]" value="')
__M_writer(filters.decode.utf8(request.POST['email']))
__M_writer(u'"></input>\n')
# SOURCE LINE 171
else :
# SOURCE LINE 172
__M_writer(u'\t\t\t\t\t\t\t<input type="input" id="signup_input_email" name="email" class="validate[optional,custom[email]]" value=""></input>\n')
pass
# SOURCE LINE 174
__M_writer(u'\t\t\t\t\t</div>\n')
pass
# SOURCE LINE 176
__M_writer(u'\t\t\t\t<div style="height:25px;"><a id="submit"></a></div>\n\t\t\t</form>\n\t\t</div>\n\t\t<div class="bottom"></div>\n\t</div>\n\t<div class="page_column_right_padding_left30">\n')
# SOURCE LINE 182
if 'method' in request.GET and request.GET['method'] == 'email' :
# SOURCE LINE 183
__M_writer(u'\t\t\t<h2>\u4e3a\u4ec0\u4e48\u6ce8\u518cFido\u9700\u8981\u624b\u673a\u53f7\uff1f</h2>\n\t\t\t<p>Fido\u793e\u533a\u63a8\u8350\u60a8\u7528\u624b\u673a\u53f7\u6ce8\u518c\u3002\u8fd9\u6837\uff0c\u60a8\u53ef\u4ee5\u6536\u5230\u6700\u65b0\u7684\u6821\u56ed\u54a8\u8baf\u3002</p>\n')
# SOURCE LINE 185
else :
# SOURCE LINE 186
__M_writer(u'\t\t\t<h2>\u4e3a\u4ec0\u4e48\u6ce8\u518cFido\u9700\u8981\u624b\u673a\u53f7\uff1f</h2>\n\t\t\t<p>Fido\u793e\u533a\u91c7\u7528<strong>\u5b9e\u540d\u5236</strong>\uff0c\u6240\u6709\u7528\u6237\u5c06\u4ee5\u624b\u673a\u53f7\u4e3aID\u767b\u5f55\u3002</p>\n\t\t\t<p>\u6211\u4eec\u5c06\u628a\u6ce8\u518c\u7684\u9a8c\u8bc1\u4fe1\u606f\u53d1\u5230\u60a8\u7684139\u90ae\u7bb1\uff0c139\u90ae\u7bb1\u7684\u767b\u5f55\u7f51\u5740\u662f<a href="http://mail.139.com/" target="_blank">mail.139.com</a>\u3002</p>\n\t\t\t<p>\u6211\u4eec\u4f1a\u5c06\u6bcf\u5929\u7684\u6700\u65b0\u8d44\u8baf\u53d1\u81f3\u60a8\u7684139\u90ae\u7bb1\u3002\u5982\u679c\u60a8\u5e0c\u671b\u5728\u7b2c\u4e00\u65f6\u95f4\u770b\u5230\u8fd9\u4e9b\u65b0\u9c9c\u8d44\u8baf\uff0c\u53ef\u4ee5\u5f00\u901a139\u90ae\u7bb1\u7684<strong>\u77ed\u4fe1\u63d0\u9192</strong>\u670d\u52a1\u3002</p>\n\t\t\t<p>\u5982\u679c\u60a8\u5e0c\u671b\u8fdb\u4e00\u6b65\u4e86\u89e3139\u90ae\u7bb1\u7684\u77ed\u4fe1\u63d0\u9192\u670d\u52a1\uff0c\u53ef\u4ee5\u67e5\u770b<a href="http://mail.10086.cn/ad/sms/sms-notice.htm" target="_blank">mail.10086.cn/ad/sms/sms-notice.htm</a>\u3002</p>\n\t\t\t<p>139\u90ae\u7bb1\u53ef\u4ee5\u901a\u8fc7\u77ed\u4fe1\u65b9\u5f0f\u5f00\u901a\uff0c\u60a8\u53ea\u9700\u7f16\u8f91\u77ed\u4fe1\u201cKTYX\u201d\u81f310086\u5373\u53ef\u3002</p>\n\t\t\t<p>\u5f53\u7136\uff0c\u60a8\u4e5f\u53ef\u4ee5\u9000\u8ba2\uff0c\u6216\u4f7f\u7528\u5176\u4ed6\u90ae\u7bb1\u6765\u63a5\u6536\u6211\u4eec\u7684\u8d44\u8baf\u3002\u60a8\u53ea\u9700\u8981\u5728\u60a8\u7684\u4e2a\u4eba\u9875\u9762\u4e2d\u8bbe\u7f6e\u76f8\u5173\u9009\u9879\u5c31\u53ef\u4ee5\u4e86\u3002</p>\n')
pass
# SOURCE LINE 194
__M_writer(u'\t</div>\n</div>\n')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1292715620.714249
_template_filename='/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/login/signup_success.mako'
_template_uri='login/signup_success.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
__M_writer = context.writer()
# SOURCE LINE 1
__M_writer(u'<div id="signup_page_bound">\n\t<h1>\u60a8\u5df2\u6ce8\u518c\u6210\u529f\uff01</h1>\n\t<div class="page_column_left_padding15">\n\t\t<div class="top"></div>\n\t\t<div class="content">\n\t\t\t<p>\u611f\u8c22\u60a8\u6ce8\u518cFido\u8d26\u53f7\u3002</p>\n\t\t\t<p>\u5982\u9700\u8981Fido\u5361\uff0c\u8bf7\u5230<a href="/login">My Fido</a>\u9875\u9762\u7533\u8bf7\u3002</p>\n\t\t</div>\n\t\t<div class="bottom"></div>\n\t</div>\n\t<div class="page_column_right_padding_left30">\n\t\t<h2>\u4e3a\u4ec0\u4e48\u6ce8\u518cFido\u9700\u8981\u624b\u673a\u53f7\uff1f</h2>\n\t\t<p>Fido\u793e\u533a\u91c7\u7528<strong>\u5b9e\u540d\u5236</strong>\uff0c\u6240\u6709\u7528\u6237\u5c06\u4ee5\u624b\u673a\u53f7\u4e3aID\u767b\u5f55\u3002</p>\n\t\t<p>\u6211\u4eec\u5c06\u628a\u6ce8\u518c\u7684\u9a8c\u8bc1\u4fe1\u606f\u53d1\u5230\u60a8\u7684139\u90ae\u7bb1\uff0c139\u90ae\u7bb1\u7684\u767b\u5f55\u7f51\u5740\u662f<a href="http://mail.139.com/" target="_blank">mail.139.com</a>\u3002</p>\n\t\t<p>\u6211\u4eec\u4f1a\u5c06\u6bcf\u5929\u7684\u6700\u65b0\u8d44\u8baf\u53d1\u81f3\u60a8\u7684139\u90ae\u7bb1\u3002\u5982\u679c\u60a8\u5e0c\u671b\u5728\u7b2c\u4e00\u65f6\u95f4\u770b\u5230\u8fd9\u4e9b\u65b0\u9c9c\u8d44\u8baf\uff0c\u53ef\u4ee5\u5f00\u901a139\u90ae\u7bb1\u7684<strong>\u77ed\u4fe1\u63d0\u9192</strong>\u670d\u52a1\u3002</p>\n\t\t<p>\u5982\u679c\u60a8\u5e0c\u671b\u8fdb\u4e00\u6b65\u4e86\u89e3139\u90ae\u7bb1\u7684\u77ed\u4fe1\u63d0\u9192\u670d\u52a1\uff0c\u53ef\u4ee5\u67e5\u770b<a href="http://mail.10086.cn/ad/sms/sms-notice.htm" target="_blank">mail.10086.cn/ad/sms/sms-notice.htm</a>\u3002</p>\n\t\t<p>139\u90ae\u7bb1\u53ef\u4ee5\u901a\u8fc7\u77ed\u4fe1\u65b9\u5f0f\u5f00\u901a\uff0c\u60a8\u53ea\u9700\u7f16\u8f91\u77ed\u4fe1\u201cKTYX\u201d\u81f310086\u5373\u53ef\u3002</p>\n\t\t<p>\u5f53\u7136\uff0c\u60a8\u4e5f\u53ef\u4ee5\u9000\u8ba2\uff0c\u6216\u4f7f\u7528\u5176\u4ed6\u90ae\u7bb1\u6765\u63a5\u6536\u6211\u4eec\u7684\u8d44\u8baf\u3002\u60a8\u53ea\u9700\u8981\u5728\u60a8\u7684\u4e2a\u4eba\u9875\u9762\u4e2d\u8bbe\u7f6e\u76f8\u5173\u9009\u9879\u5c31\u53ef\u4ee5\u4e86\u3002</p>\n\t</div>\n</div>\n')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1292685650.772242
_template_filename='/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/login/content.mako'
_template_uri='login/content.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
c = context.get('c', UNDEFINED)
__M_writer = context.writer()
# SOURCE LINE 1
c.jsFiles.append('/script/login/login.js?v=10')
# SOURCE LINE 3
__M_writer(u'\n<div id="content_bound">\n\t<style type="text/css">#mylist #list_item:hover{background-color:#F9F9F9;}</style>\n')
# SOURCE LINE 6
if c.loginUser == None :
# SOURCE LINE 7
__M_writer(u'\t<h1>\u8bf7\u767b\u5f55\u3002</h1>\n')
# SOURCE LINE 8
else :
# SOURCE LINE 9
__M_writer(u'\t<h1>\u6b22\u8fce\uff0c')
__M_writer(filters.decode.utf8(c.loginUser.name))
__M_writer(u'\uff01</h1>\t\n\t<div>\n\t\t<div class="page_column_left_padding15">\n\t\t\t<div class="top"></div>\n\t\t\t<div class="content">\n\t\t\t\t<div style="clear:both;"></div>\n\t\t\t\t<div id="mylist"></div>\n\t\t\t\t<div style="clear:both;"></div>\n\t\t\t\t<div id="mylist_item_maploc_example" class="hidden_example">\n\t\t\t\t\t<div id="list_item" style="border-top:1px solid #DDDDDD;padding:5px;cursor:pointer;">\n\t\t\t\t\t\t<div id="loc_id" style="display:none;"></div>\n\t\t\t\t\t\t<div style="clear:both;">\n\t\t\t\t\t\t\t<span id="loc_name" style="font-size:14px;"></span>\n\t\t\t\t\t\t\t<span id="loc_rating" class="star-rating" style="width:75px;display:inline-block;float:right;"></span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div id="loc_address" style="color:#A1A0A0;"></div>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t<div id="mylist_item_topic_example" class="hidden_example">\n\t\t\t\t\t<div id="list_item" style="border-top:1px solid #DDDDDD;padding:5px;cursor:pointer;">\n\t\t\t\t\t\t<div id="topic_id" style="display:none;"></div>\n\t\t\t\t\t\t<div style="clear:both;">\n\t\t\t\t\t\t\t<div id="topic_title" style="font-size:14px;"></div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div style="color:#A1A0A0;">\n\t\t\t\t\t\t\t\u5730\u70b9\uff1a<span id="topic_maploc" style="display:inline-block;"></span> - \n\t\t\t\t\t\t\t\u56de\u590d\uff1a<span id="topic_postcount" style="display:inline-block;"></span> - \n\t\t\t\t\t\t\t\u66f4\u65b0\u65f6\u95f4\uff1a<span id="topic_updatetime" style="display:inline-block;"></span> - \n\t\t\t\t\t\t\t\u521b\u5efa\u65f6\u95f4\uff1a<span id="topic_createtime" style="display:inline-block;"></span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t<div id="mylist_item_post_example" class="hidden_example">\n\t\t\t\t\t<div id="list_item" style="border-top:1px solid #DDDDDD;padding:5px;cursor:pointer;">\n\t\t\t\t\t\t<div id="topic_id" style="display:none;"></div>\n\t\t\t\t\t\t<div style="clear:both;">\n\t\t\t\t\t\t\t<div id="post_content" style="font-size:14px;"></div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div style="color:#A1A0A0;">\n\t\t\t\t\t\t\t\u8bdd\u9898\uff1a<span id="post_topic_title" style="display:inline-block;"></span> - \n\t\t\t\t\t\t\t\u521b\u5efa\u65f6\u95f4\uff1a<span id="post_createtime" style="display:inline-block;"></span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<div class="bottom"></div>\n\t\t</div>\n\t\t<div class="page_column_right_padding_left30">\n\t\t\t<h2>\u6ca1\u6709Fido\u5361\uff1f</h2>\n\t\t\t<p>\u5982\u679c\u60a8\u6ca1\u6709Fido\u5361\uff0c\u8bf7\u70b9\u51fb<a id="link_apply_card" href="javascript:void(0)">\u8fd9\u91cc</a>\u7533\u8bf7\u3002</p>\n\t\t\t<p>\u7533\u8bf7\u63d0\u4ea4\u4e09\u5929\u540e\uff0c\u60a8\u53ef\u4ee5\u5230Fido\u7684\u5408\u4f5c\u5546\u6237\u6362\u53d6Fido\u5361\uff08\u9700\u652f\u4ed85\u5143\u7684\u6210\u672c\u8d39\uff09\u3002</p>\n\t\t\t<p>\u76ee\u524d\uff0cFido\u5361\u5c06\u5728<strong>90\u751f\u6d3b\u6587\u5316\u9986</strong>\uff08\u5730\u5740\uff1a\u590d\u65e6\u5927\u5b66\u5357\u533a\u4e00\u6761\u885711\u53f7\uff09\u53d1\u653e\uff0c\u53d1\u653e\u65f6\u95f4\u4e3a<strong>\u6bcf\u5468\u5468\u4e00\u81f3\u5468\u56db</strong>\u3002</p>\n\t\t</div>\n\t</div>\n')
pass
# SOURCE LINE 64
__M_writer(u'</div>')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1292757740.147426
_template_filename='/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/login/login.mako'
_template_uri='login/login.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
__M_writer = context.writer()
# SOURCE LINE 1
__M_writer(u'<style type="text/css">\n.button_login{\n\tbottom:0;\n\tright:0;\n\tcursor:pointer;\n\tposition:absolute;\n\tfloat:left;\n\twidth:130px;\n\theight:45px;\n\tbackground:url(\'/image/global/button_login.png\');\n}\n.button_login:hover{background-position:0 -45px;}\n</style>\n<script type="text/javascript">\nfunction validateUsername(){\n\tvar username = $("#form_login #login_input_username").val();\n\tif (username.match("@") == null){\n\t\tif (!isValidMobile(username)) return false;\n\t\treturn true;\n\t} else {\n\t\tif (!isValidEmail(username)) return false;\n\t\treturn true;\n\t} \n}\nfunction validatePassword(){\n\tvar password = $("#form_login #login_input_password").val();\n\treturn isValidPassword(password);\n}\n$(document).ready(function(){\n\t$("#form_login").validationEngine();\n\n\t$("#button_login").click(function(){\n\t\t$.validationEngine.submitValidation("#form_login"); \n\t\tvar obj = this;\n\t\tvar username = $("#form_login #login_input_username").val();\n\t\tvar password = $("#form_login #login_input_password").val();\n\t\tif (!validateUsername()) return;\n\t\tif (!validatePassword()) return;\n\t\t$.validationEngine.buildPrompt("form #button_login", "\u6b63\u5728\u63d0\u4ea4\uff0c\u8bf7\u7a0d\u5019\u3002", "load");\n\t\t$.post("/login/getLoginCode", function(data){\n\t\t\tpassword = hex_sha512(data + hex_sha512(password));\n\t\t\t$.post("/login/doLogin", {username : username, password : password}, function(data){\n\t\t\t\tif (data == "success"){\n\t\t\t\t\t$.validationEngine.buildPrompt("#form_login #button_login", "\u767b\u5f55\u6210\u529f\uff01", "pass");\n\t\t\t\t\twindow.location.reload(); \n\t\t\t\t} else if (data == "wrong username"){\n\t\t\t\t\t$.validationEngine.buildPrompt("#form_login #login_input_username", "\u60a8\u8f93\u5165\u7684\u624b\u673a\u53f7\u6216\u90ae\u7bb1\u4e0d\u6b63\u786e\uff0c\u8bf7\u91cd\u65b0\u8f93\u5165\u3002", "error");\n\t\t\t\t} else if (data == "wrong password"){\n\t\t\t\t\t$.validationEngine.buildPrompt("#form_login #login_input_password", "\u9519\u8bef\u7684\u5bc6\u7801\uff0c\u8bf7\u91cd\u65b0\u8f93\u5165\u3002", "error");\n\t\t\t\t} else if (data == "too fast"){\n\t\t\t\t\t$.validationEngine.buildPrompt("#form_login #button_login", "\u60a8\u7684\u767b\u5f55\u64cd\u4f5c\u8fc7\u4e8e\u9891\u7e41\uff0c\u8bf7\u7a0d\u5019\u5c1d\u8bd5\u3002", "error");\n\t\t\t\t} else {\n\t\t\t\t\t$.validationEngine.buildPrompt("#form_login #button_login", "\u767b\u5f55\u5931\u8d25\u3002", "error");\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t});\n});\n</script>\n<div id="login_bound">\n\t<div class="page_column_left_padding15">\n\t\t<h1>\u767b\u5f55</h1>\n\t\t<div class="top"></div>\n\t\t<div class="content">\n\t\t\t<form id="form_login">\n\t\t\t\t<div id="login_mobile">\n\t\t\t\t\t<label>\u7528\u6237\u540d</label>\n\t\t\t\t\t<input id="login_input_username" type="text" name="mobile" class="validate[required,funcCall[validateUsername]]"></input>\n\t\t\t\t\t<span style="padding-left:20px;color:gray;">\uff08\u7528\u624b\u673a\u53f7\u6216\u90ae\u7bb1\u767b\u5f55\uff09</span>\n\t\t\t\t</div>\n\t\t\t\t<div id="login_password">\n\t\t\t\t\t<label>\u5bc6\u7801</label>\n\t\t\t\t\t<input id="login_input_password" type="password" name="password" class="validate[required,funcCall[validatePassword]]"></input>\n\t\t\t\t</div>\n\t\t\t\t<div id="bottom_buttons" style="clear:both;position:relative;">\n\t\t\t\t\t<span><a href="/login/forgetPassword" style="position:absolute;left:10px;top:10px;">\u5fd8\u8bb0\u5bc6\u7801\uff1f</a></span>\n\t\t\t\t\t<span id="button_login" class="button_login"></span>\n\t\t\t\t</div>\n\t\t\t</form>\n\t\t</div>\n\t\t<div class="bottom"></div>\n\t</div>\n</div>\n')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1293141039.59392
_template_filename='/home/sunzheng/Projects/FidoWeb/FidoWeb_0.98/fidoweb/templates/login/settings.mako'
_template_uri='login/settings.mako'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
c = context.get('c', UNDEFINED)
__M_writer = context.writer()
# SOURCE LINE 1
c.jsFiles.append('/script/login/settings.js')
# SOURCE LINE 3
__M_writer(u'\n<div id="mysettings">\n')
# SOURCE LINE 5
if c.loginUser == None :
# SOURCE LINE 6
__M_writer(u'\t<h1>\u8bf7\u767b\u5f55\u3002</h1>\n')
# SOURCE LINE 7
else :
# SOURCE LINE 8
__M_writer(u'\t<h1>\u6b22\u8fce\uff0c')
__M_writer(filters.decode.utf8(c.loginUser.name))
__M_writer(u'\uff01</h1>\n\t<div>\n\t\t<div class="page_column_left_padding15">\n\t\t\t<div class="top"></div>\n\t\t\t<div class="content">\n\t\t\t\t<div>\u5bc6\u7801\uff1a<a id="inline" href="#dialog_changepass" rel="prettyPhoto"><img style="display:none;" alt="\u4fee\u6539\u5bc6\u7801"></img>\u4fee\u6539</a></div>\n\t\t\t\t<div id="dialog_changepass" class="hidden_example">\n\t\t\t\t\t<div id="form_changepass">\n\t\t\t\t\t\t<form>\n\t\t\t\t\t\t\t<div id="changepass_oldpass">\n\t\t\t\t\t\t\t\t<label>\u65e7\u5bc6\u7801</label>\n\t\t\t\t\t\t\t\t<input type="password" name="oldpass" class="validate[required,funcCall[validateOldPass]]" id="input_oldpass"></input>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div id="changepass_password">\n\t\t\t\t\t\t\t\t<label>\u65b0\u5bc6\u7801</label>\n\t\t\t\t\t\t\t\t<input type="password" name="newpass" class="validate[required,funcCall[validateNewPass]]" id="input_newpass"></input>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div id="changepass_password">\n\t\t\t\t\t\t\t\t<label>\u786e\u8ba4\u5bc6\u7801</label>\n\t\t\t\t\t\t\t\t<input type="password" name="retype_pass" class="validate[required,funcCall[validateRetypePass]]" id="input_retype_pass"></input>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div id="bottom_buttons" style="margin:0;padding:0;line-height:25px;">\n\t\t\t\t\t\t\t\t<a id="button_submit" href="javascript:settingsCtrl.processSubmit();">\u786e\u8ba4</a>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</form>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t<div>\u751f\u65e5\uff1a\n')
# SOURCE LINE 36
if c.loginUser.birthday != None :
# SOURCE LINE 37
__M_writer(u'\t\t\t\t\t\t')
__M_writer(filters.decode.utf8(c.loginUser.birthday.strftime('%Y-%m-%d')))
__M_writer(u'\n')
# SOURCE LINE 38
else :
# SOURCE LINE 39
__M_writer(u'\t\t\t\t\t\t\u672a\u77e5\n')
pass
# SOURCE LINE 41
__M_writer(u'\t\t\t\t</div>\n\t\t\t\t<div>\u90ae\u7bb1\uff1a\n')
# SOURCE LINE 43
if c.loginUser.email != None :
# SOURCE LINE 44
__M_writer(u'\t\t\t\t\t\t')
__M_writer(filters.decode.utf8(c.loginUser.email))
__M_writer(u'\n')
# SOURCE LINE 45
else :
# SOURCE LINE 46
__M_writer(u'\t\t\t\t\t\t\u672a\u7ed1\u5b9a\n')
pass
# SOURCE LINE 48
__M_writer(u'\t\t\t\t</div>\n\t\t\t\t<div>\u624b\u673a\uff1a\n')
# SOURCE LINE 50
if c.loginUser.mobile != None :
# SOURCE LINE 51
__M_writer(u'\t\t\t\t\t\t')
__M_writer(filters.decode.utf8(c.loginUser.mobile[:3] + '****' + c.loginUser.mobile[7:]))
__M_writer(u'\n')
# SOURCE LINE 52
else :
# SOURCE LINE 53
__M_writer(u'\t\t\t\t\t\t\u672a\u7ed1\u5b9a\n')
pass
# SOURCE LINE 55
__M_writer(u'\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<div class="bottom"></div>\n\t\t</div>\n\t\t<div class="page_column_right_padding_left30"></div>\n\t</div>\n')
pass
# SOURCE LINE 62
__M_writer(u'</div>')
return ''
finally:
context.caller_stack._pop_frame()
| Python |
#!python
"""Bootstrap setuptools installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptools, set a download
mirror, or use an alternate download directory, you can do so by supplying
the appropriate options to ``use_setuptools()``.
This file can also be run as a script to install or upgrade setuptools.
"""
import sys
DEFAULT_VERSION = "0.6c9"
DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]
md5_data = {
'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',
'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb',
'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b',
'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a',
'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618',
'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac',
'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5',
'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4',
'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c',
'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b',
'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27',
'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277',
'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa',
'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e',
'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e',
'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f',
'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2',
'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc',
'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167',
'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64',
'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d',
'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20',
'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab',
'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53',
'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',
'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',
'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',
'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902',
'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de',
'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b',
'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03',
'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a',
'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6',
'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a',
}
import sys, os
try: from hashlib import md5
except ImportError: from md5 import md5
def _validate_md5(egg_name, data):
if egg_name in md5_data:
digest = md5(data).hexdigest()
if digest != md5_data[egg_name]:
print >>sys.stderr, (
"md5 validation of %s failed! (Possible download problem?)"
% egg_name
)
sys.exit(2)
return data
def use_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
download_delay=15
):
"""Automatically find/download setuptools and make it available on sys.path
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end with
a '/'). `to_dir` is the directory where setuptools will be downloaded, if
it is not already available. If `download_delay` is specified, it should
be the number of seconds that will be paused before initiating a download,
should one be required. If an older version of setuptools is installed,
this routine will print a message to ``sys.stderr`` and raise SystemExit in
an attempt to abort the calling script.
"""
was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules
def do_download():
egg = download_setuptools(version, download_base, to_dir, download_delay)
sys.path.insert(0, egg)
import setuptools; setuptools.bootstrap_install_from = egg
try:
import pkg_resources
except ImportError:
return do_download()
try:
pkg_resources.require("setuptools>="+version); return
except pkg_resources.VersionConflict, e:
if was_imported:
print >>sys.stderr, (
"The required version of setuptools (>=%s) is not available, and\n"
"can't be installed while this script is running. Please install\n"
" a more recent version first, using 'easy_install -U setuptools'."
"\n\n(Currently using %r)"
) % (version, e.args[0])
sys.exit(2)
else:
del pkg_resources, sys.modules['pkg_resources'] # reload ok
return do_download()
except pkg_resources.DistributionNotFound:
return do_download()
def download_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
delay = 15
):
"""Download setuptools from a specified location and return its filename
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download attempt.
"""
import urllib2, shutil
egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
url = download_base + egg_name
saveto = os.path.join(to_dir, egg_name)
src = dst = None
if not os.path.exists(saveto): # Avoid repeated downloads
try:
from distutils import log
if delay:
log.warn("""
---------------------------------------------------------------------------
This script requires setuptools version %s to run (even to display
help). I will attempt to download it for you (from
%s), but
you may need to enable firewall access for this script first.
I will start the download in %d seconds.
(Note: if this machine does not have network access, please obtain the file
%s
and place it in this directory before rerunning this script.)
---------------------------------------------------------------------------""",
version, download_base, delay, url
); from time import sleep; sleep(delay)
log.warn("Downloading %s", url)
src = urllib2.urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = _validate_md5(egg_name, src.read())
dst = open(saveto,"wb"); dst.write(data)
finally:
if src: src.close()
if dst: dst.close()
return os.path.realpath(saveto)
def main(argv, version=DEFAULT_VERSION):
"""Install or upgrade setuptools and EasyInstall"""
try:
import setuptools
except ImportError:
egg = None
try:
egg = download_setuptools(version, delay=0)
sys.path.insert(0,egg)
from setuptools.command.easy_install import main
return main(list(argv)+[egg]) # we're done here
finally:
if egg and os.path.exists(egg):
os.unlink(egg)
else:
if setuptools.__version__ == '0.0.1':
print >>sys.stderr, (
"You have an obsolete version of setuptools installed. Please\n"
"remove it from your system entirely before rerunning this script."
)
sys.exit(2)
req = "setuptools>="+version
import pkg_resources
try:
pkg_resources.require(req)
except pkg_resources.VersionConflict:
try:
from setuptools.command.easy_install import main
except ImportError:
from easy_install import main
main(list(argv)+[download_setuptools(delay=0)])
sys.exit(0) # try to force an exit
else:
if argv:
from setuptools.command.easy_install import main
main(argv)
else:
print "Setuptools version",version,"or greater has been installed."
print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
def update_md5(filenames):
"""Update our built-in md5 registry"""
import re
for name in filenames:
base = os.path.basename(name)
f = open(name,'rb')
md5_data[base] = md5(f.read()).hexdigest()
f.close()
data = [" %r: %r,\n" % it for it in md5_data.items()]
data.sort()
repl = "".join(data)
import inspect
srcfile = inspect.getsourcefile(sys.modules[__name__])
f = open(srcfile, 'rb'); src = f.read(); f.close()
match = re.search("\nmd5_data = {\n([^}]+)}", src)
if not match:
print >>sys.stderr, "Internal error!"
sys.exit(2)
src = src[:match.start(1)] + repl + src[match.end(1):]
f = open(srcfile,'w')
f.write(src)
f.close()
if __name__=='__main__':
if len(sys.argv)>2 and sys.argv[1]=='--md5update':
update_md5(sys.argv[2:])
else:
main(sys.argv[1:])
| Python |
from sqlalchemy import Table, Column, ForeignKey
from sqlalchemy.orm import relation, backref, deferred, mapper
from sqlalchemy.types import BigInteger, Integer, String, DateTime
from sqlalchemy.dialects.mysql import ENUM
from fidoweb.model.meta import Base
from fidoweb.model.map import School
"""
Rules
1. Tables and Inner relations are sorted in alphabet order, and Inner relations are defined after Tables
2. About relations:
For m-m relations: 'relation' defined in the first element of the relation
For o-m(m-o) relations: 'relation' defined in the element of 'm' side
"""
"""
Tables
City
Country
State
"""
"""
Inner relations
City(state) m-o State(cities)
Country(states) o-m State(country)
"""
"""
Outer relations
City(schools) o-m School(city)
"""
City_t = Table('cities', Base.metadata,
Column('id', Integer, primary_key = True),
Column('name', String(64), unique = True),
Column('state_id', Integer, ForeignKey('states.id')),
)
Country_t = Table('countries', Base.metadata,
Column('id', Integer, primary_key = True),
Column('name', String(64), unique = True),
)
State_t = Table('states', Base.metadata,
Column('id', Integer, primary_key = True),
Column('name', String(64), unique = True),
Column('country_id', Integer, ForeignKey('countries.id')),
)
class City(object) :
def __init__(self, name, state_id) :
self.name = name
self.state_id = state_id
class Country(object) :
def __init__(self, name) :
self.name = name
class State(object) :
def __init__(self, name, country_id) :
self.name = name
self.country_id = country_id
mapper(City, City_t, properties = {
'id' : City_t.c.id,
'name' : City_t.c.name,
'state_id' : City_t.c.state_id,
'schools' : relation(School, backref = 'city'),
})
mapper(Country, Country_t, properties = {
'id' : Country_t.c.id,
'name' : Country_t.c.name,
'states' : relation(State, backref = 'country'),
})
mapper(State, State_t, properties = {
'id' : State_t.c.id,
'name' : State_t.c.name,
'country_id' : State_t.c.country_id,
'cities' : relation(City, backref = 'state'),
}) | Python |
import datetime
from sqlalchemy import Table, Column, ForeignKey
from sqlalchemy.orm import relation, backref, mapper
from sqlalchemy.types import BigInteger, Integer, String, DateTime, Text, Boolean, Date
from sqlalchemy.dialects.mysql import ENUM
from fidoweb.model.meta import Base
"""
Rules
1. Tables and Inner relations are sorted in alphabet order, and Inner relations are defined after Tables
2. About relations:
For m-m and o-o relations: 'relation' defined in the first element of the relation
For o-m(m-o) relations: 'relation' defined in the element of 'm' side
"""
"""
Tables
CardApplication
Department
OAPrivateMsg
OAPrivateTask
OAUser
Profession
SignUpMobile
User
UserGroup
UserNotification
UserNotificationType
"""
"""
Inner relations
CardApplication(user) o-o User(application)
Department(OAUsers) o-m OAUser(department)
OAPrivateMsg(OAUser) m-o OAUser(privateMsgs)
OAPrivateTask(OAUser) m-o OAUser(privateTasks)
User(userGroups) m-m UserGroup(users)
User(notifications) o-m UserNotification(user)
UserNotification(type) m-o UserNotificationType(notifications)
"""
"""
Outer relations
CardApplication(seller) m-o CardSeller(applications)
Discount(users) m-m User(discounts) (Describing how much a user like the discount)
Media139MailTypes(users) m-m User(media139MailTypes) (Describing whether a user need a certain kind of Fido Media)
School(users) m-m User(schools) (Describing what schools a user has been to, including the profession)
SchoolMapLoc(users) m-m User(schoolMapLocs) (Describing how much a user like the location)
SchoolMapLocComment(user) m-o User(schoolMapLocComments)
"""
CardApplication_t = Table('cardApplications', Base.metadata,
Column('id', BigInteger, ForeignKey('users.id'), primary_key = True),
Column('updateTime', DateTime(timezone = True), index = True),
Column('cardSeller_id', BigInteger, ForeignKey('cardSellers.id')),
)
Department_t = Table('departments', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('name', String(32), unique = True),
)
OAPrivateMsg_t = Table('OAPrivateMsgs', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('description', Text),
Column('createTime', DateTime(timezone = True), index = True),
Column('user_id', BigInteger, ForeignKey('OAUsers.id')),
)
OAPrivateTask_t = Table('OAPrivateTasks', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('user_id', BigInteger, ForeignKey('OAUsers.id')),
Column('name', String(64)),
Column('description', Text),
Column('createTime', DateTime(timezone = True), index = True),
Column('deadline', DateTime(timezone = True), index = True),
Column('finishTime', DateTime(timezone = True), index = True),
)
OAUser_t = Table('OAUsers', Base.metadata,
Column('id', BigInteger, ForeignKey('users.id'), primary_key = True),
Column('department_id', BigInteger, ForeignKey('departments.id')),
)
Profession_t = Table('professions', Base.metadata,
Column('id', Integer, primary_key = True),
Column('name', String(64), unique = True),
)
SignUpEmail_t = Table('signUpEmails', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('email', String(128), unique = True),
Column('authCode', String(8), index = True),
Column('updateTime', DateTime(timezone = True), index = True),
)
SignUpMobile_t = Table('signUpMobiles', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('mobile', String(11), unique = True),
Column('authCode', String(8), index = True),
Column('updateTime', DateTime(timezone = True), index = True)
)
User_t = Table('users', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('name', String(32), index = True),
Column('password', String(128)),
Column('gender', ENUM('male', 'female'), index = True),
Column('mobile', String(11), unique = True),
Column('birthday', Date(timezone = True), index = True),
Column('createTime', DateTime(timezone = True), index = True),
Column('fidoPoints', Integer, index = True),
Column('email', String(128), unique = True),
Column('fidocard', String(19), unique = True),
Column('updateTime', DateTime(timezone = True), index = True),
Column('activeTime', Integer, index = True),
)
UserGroup_t = Table('userGroups', Base.metadata,
Column('id', Integer, primary_key = True),
Column('name', String(128), unique = True),
Column('description', String(300)),
Column('parent_id', Integer, ForeignKey('userGroups.id'))
)
UserNotification_t = Table('userNotifications', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('user_id', BigInteger, ForeignKey('users.id')),
Column('additionalId', BigInteger, index = True), # store the id of an object, if necessary
Column('repeatedTimes', Integer, index = True), # store how many time that the notification is repeated
Column('type_id', Integer, ForeignKey('userNotificationTypes.id')),
Column('createTime', DateTime(timezone = True), index = True),
Column('updateTime', DateTime(timezone = True), index = True),
Column('content', Text),
)
UserNotificationType_t = Table('userNotificationTypes', Base.metadata,
Column('id', Integer, primary_key = True),
Column('name', String(64), unique = True),
)
User_UserGroup_t = Table('users_userGroups', Base.metadata,
Column('user_id', ForeignKey('users.id'), primary_key = True),
Column('userGroup_id', ForeignKey('userGroups.id'), primary_key = True),
)
class CardApplication(object) :
def __init__(self, user_id, cardSeller_id) :
self.id = user_id
self.cardSeller_id = cardSeller_id
self.updateTime = datetime.datetime.now()
class Department(object) :
def __init__(self, name) :
self.name = name
class OAPrivateMsg(object) :
def __init__(self, user_id, description) :
self.user_id = user_id
self.description = description
self.createTime = datetime.datetime.now()
class OAPrivateTask(object) :
def __init__(self, user_id, name, description, deadline) :
self.name = name
self.user_id = user_id
self.description = description
self.createTime = now
self.deadline = deadline
self.finishTime = NULL
class OAUser(object) :
def __init__(self, id, department_id) :
self.id = id
self.department_id = department_id
class Profession(object) :
def __init__(self, name) :
self.name = name
class SignUpEmail(object) :
def __init__(self, email, authCode) :
self.email = email
self.authCode = authCode
self.updateTime = datetime.datetime.now()
class SignUpMobile(object) :
def __init__(self, mobile, authCode) :
self.mobile = mobile
self.authCode = authCode
self.updateTime = datetime.datetime.now()
class User(object) :
def __init__(self, fidocard, name, password, gender, mobile, birthday, email) :
self.name = name
self.password = password
self.gender = gender
self.mobile = mobile
self.birthday = birthday
self.email = email
self.createTime = datetime.datetime.now()
self.fidocard = fidocard
self.fidoPoints = 0
self.updateTime = None
self.activeTime = 0
class UserGroup(object) :
def __init__(self, name, description, parent_id) :
self.name = name
self.description = description
self.parent_id = parent_id
class UserNotification(object) :
def __init__(self, user_id, additionalId, type_id, content) :
self.user_id = user_id
self.additionalId = additionalId
self.type_id = type_id
self.content = content
self.repeatedTimes = 1
self.createTime = datetime.datetime.now()
self.updateTime = datetime.datetime.now()
class UserNotificationType(object) :
def __init__(self, name) :
self.name = name
class User_UserGroup(object) :
def __init__(self, user_id, userGroup_id) :
self.user_id = user_id
self.userGroup_id = userGroup_id
from fidoweb.model.map import SchoolMapLocTopic, SchoolMapLocTopicPost
mapper(CardApplication, CardApplication_t, properties = {
'id' : CardApplication_t.c.id,
'updateTime' : CardApplication_t.c.updateTime,
'cardSeller_id' : CardApplication_t.c.cardSeller_id,
'user' : relation(User, backref = 'application')
})
mapper(Department, Department_t, properties = {
'id' : Department_t.c.id,
'name' : Department_t.c.name,
'OAUsers' : relation(OAUser, backref = 'department'),
})
mapper(OAPrivateMsg, OAPrivateMsg_t, properties = {
'id' : OAPrivateMsg_t.c.id,
'description' : OAPrivateMsg_t.c.description,
'createTime' : OAPrivateMsg_t.c.createTime,
'user_id' : OAPrivateMsg_t.c.user_id,
})
mapper(OAPrivateTask, OAPrivateTask_t, properties = {
'id' : OAPrivateTask_t.c.id,
'user_id' : OAPrivateTask_t.c.user_id,
'name' : OAPrivateTask_t.c.name,
'description' : OAPrivateTask_t.c.description,
'createTime' : OAPrivateTask_t.c.createTime,
'deadline' : OAPrivateTask_t.c.deadline,
'finishTime' : OAPrivateTask_t.c.finishTime,
})
mapper(OAUser, OAUser_t, properties = {
'id' : OAUser_t.c.id,
'department_id' : OAUser_t.c.department_id,
'privateMsgs' : relation(OAPrivateMsg, backref = 'OAUser'),
'privateTasks' : relation(OAPrivateTask, backref = 'OAUser'),
})
mapper(Profession, Profession_t, properties = {
'id' : Profession_t.c.id,
'name' : Profession_t.c.name,
})
mapper(SignUpEmail, SignUpEmail_t, properties = {
'id' : SignUpEmail_t.c.id,
'email' : SignUpEmail_t.c.email,
'authCode' : SignUpEmail_t.c.authCode,
'updateTime' : SignUpEmail_t.c.updateTime
})
mapper(SignUpMobile, SignUpMobile_t, properties = {
'id' : SignUpMobile_t.c.id,
'mobile' : SignUpMobile_t.c.mobile,
'authCode' : SignUpMobile_t.c.authCode,
'updateTime' : SignUpMobile_t.c.updateTime
})
mapper(User, User_t, properties = {
'id' : User_t.c.id,
'name' : User_t.c.name,
'password' : User_t.c.password,
'gender' : User_t.c.gender,
'mobile' : User_t.c.mobile,
'birthday' : User_t.c.birthday,
'createTime' : User_t.c.createTime,
'fidoPoints' : User_t.c.fidoPoints,
'email' : User_t.c.email,
'fidocard' : User_t.c.fidocard,
'updateTime' : User_t.c.updateTime,
'activeTime' : User_t.c.activeTime,
'userGroups' : relation(UserGroup, secondary = User_UserGroup_t, backref = 'users'),
'schoolMapLocTopics' : relation(SchoolMapLocTopic, backref = 'user'),
'schoolMapLocTopicPosts' : relation(SchoolMapLocTopicPost, backref = 'user'),
'notifications' : relation(UserNotification, backref = 'user'),
})
mapper(UserGroup, UserGroup_t, properties = {
'id' : UserGroup_t.c.id,
'name' : UserGroup_t.c.name,
'description' : UserGroup_t.c.description,
'parent_id' : UserGroup_t.c.parent_id,
})
mapper(UserNotification, UserNotification_t, properties = {
'id' : UserNotification_t.c.id,
'user_id' : UserNotification_t.c.user_id,
'additionalId' : UserNotification_t.c.additionalId,
'repeatedTimes' : UserNotification_t.c.repeatedTimes,
'type_id' : UserNotification_t.c.type_id,
'createTime' : UserNotification_t.c.createTime,
'updateTime' : UserNotification_t.c.updateTime,
'content' : UserNotification_t.c.content,
})
mapper(UserNotificationType, UserNotificationType_t, properties = {
'id' : UserNotificationType_t.c.id,
'name' : UserNotificationType_t.c.name,
'notifications' : relation(UserNotification, backref = 'type'),
})
mapper(User_UserGroup, User_UserGroup_t, properties = {
'user_id' : User_UserGroup_t.c.user_id,
'userGroup_id' : User_UserGroup_t.c.userGroup_id,
}) | Python |
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, ForeignKey
from sqlalchemy.orm import relation, backref
from sqlalchemy.types import Integer, Unicode
from fidoweb.model.meta import Base
class HomepageGalleryPicType(Base) :
__tablename__ = 'homepageGalleryPicTypes'
id = Column(Integer, primary_key = True)
name = Column(Unicode(20))
def __init__(self, name = '') :
self.name = name
class HomepageGalleryPic(Base) :
__tablename__ = 'homepageGalleryPics'
id = Column(Integer, primary_key = True)
title = Column(Unicode(20))
url = Column(Unicode(100))
type_id = Column(Integer, ForeignKey('homepageGalleryPicTypes.id'))
type = relation(HomepageGalleryPicType, backref = backref('pics', order_by = id))
def __init__(self, type, title = '', url = '') :
self.type = type
self.title = title
self.url = url
| Python |
import datetime
from sqlalchemy import Table, Column, ForeignKey
from sqlalchemy.orm import relation, backref, mapper, deferred
from sqlalchemy.types import BigInteger, Integer, String, DateTime, Text, Float, Numeric, SmallInteger
from sqlalchemy.dialects.mysql import ENUM
from fidoweb.model.meta import Base
"""
Rules
1. Tables and Inner relations are sorted in alphabet order, and Inner relations are defined after Tables
2. About relations:
For m-m and o-o relations: 'relation' defined in the first element of the relation
For o-m(m-o) relations: 'relation' defined in the element of 'm' side
"""
"""
Tables
CardSeller
Discount
School
SchoolMap
SchoolMapDefault
SchoolMapGoogle
SchoolMapLoc
SchoolMapLocPic
SchoolMapLocType
SchoolMapLocTopic
SchoolMapLocTopicPost
SchoolMapPiece
SchoolType
Store
"""
"""
Inner relations
CardSeller(mapLoc) o-o SchoolMapLoc(cardSeller)
Discount(store) m-o Store(discounts)
School(type) m-o SchoolType(schools)
School(maps) o-m SchoolMap(school)
SchoolMap(defaultMap) o-o SchoolMapDefault(schoolMap)
SchoolMap(googleMap) o-o SchoolMapGoogle(schoolMap)
SchoolMapDefault(mapPieces) o-m SchoolMapPiece(map)
SchoolMapDefault(mapLocs) m-m SchoolMapLoc(defaultMaps)
SchoolMapGoogle(mapLocs) m-m SchoolMapLoc(googleMaps)
SchoolMapLoc(pics) o-m SchoolMapLocPic(mapLoc)
SchoolMapLoc(types) m-m SchoolMapLocType(mapLocs)
SchoolMapLoc(topics) o-m SchoolMapLocTopic(mapLoc)
SchoolMapLoc(store) o-o Store(mapLoc)
SchoolMapLocTopic(posts) o-m SchoolMapLocTopicPost(topic)
"""
"""
Outer relations
CardApplication(seller) m-o CardSeller(applications)
City(schools) o-m School(city)
Discount(users) m-m User(discounts) (Describing how much a user like the discount)
School(users) m-m User(schools) (Describing what schools a user has been to, including the profession)
SchoolMapLoc(users) m-m User(schoolMapLocs) (Describing how much a user like the location)
SchoolMapLocTopic(user) m-o User(schoolMapLocTopics)
SchoolMapLocTopicPost(user) m-o User(schoolMapLocTopicPosts)
"""
CardSeller_t = Table('cardSellers', Base.metadata,
Column('id', BigInteger, ForeignKey('schoolMapLocs.id'), primary_key = True),
Column('description', Text)
)
Discount_t = Table('discounts', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('name', String(200)),
Column('createTime', DateTime(timezone = True), index = True),
Column('validTime', DateTime(timezone = True), index = True),
Column('expireTime', DateTime(timezone = True), index = True),
Column('largePic', String(256)),
Column('smallPic', String(256)),
Column('store_id', BigInteger, ForeignKey('stores.id'))
)
School_t = Table('schools', Base.metadata,
Column('id', Integer, primary_key = True),
Column('name', String(64), unique = True),
Column('type_id', Integer, ForeignKey('schoolTypes.id')),
Column('city_id', Integer, ForeignKey('cities.id'))
)
SchoolMap_t = Table('schoolMaps', Base.metadata,
Column('id', Integer, primary_key = True),
Column('name', String(128), unique = True),
Column('school_id', Integer, ForeignKey('schools.id')),
)
SchoolMapDefault_t = Table('schoolMapsDefault', Base.metadata,
Column('id', Integer, ForeignKey('schoolMaps.id'), primary_key = True),
Column('width', Integer),
Column('height', Integer)
)
SchoolMapGoogle_t = Table('schoolMapsGoogle', Base.metadata,
Column('id', Integer, ForeignKey('schoolMaps.id'), primary_key = True),
Column('zoom', Integer),
Column('posX', Numeric(precision = 16, scale = 12)),
Column('posY', Numeric(precision = 16, scale = 12))
)
SchoolMapLoc_t = Table('schoolMapLocs', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('name', String(64), index = True),
Column('address', String(256), index = True),
Column('updateTime', DateTime(timezone = True), index = True),
Column('visitCount', BigInteger, index = True),
Column('avgRating', Float, index = True),
Column('topicCount', BigInteger, index = True),
Column('ranking', Float, index = True),
Column('description', Text),
)
SchoolMapLocPic_t = Table('schoolMapLocPics', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('schoolMapLoc_id', BigInteger, ForeignKey('schoolMapLocs.id')),
Column('picCode', String(16), unique = True),
Column('createTime', DateTime(timezone = True), index = True),
Column('largePic', String(256)),
Column('smallPic', String(256))
)
SchoolMapLocType_t = Table('schoolMapLocTypes', Base.metadata,
Column('id', Integer, primary_key = True),
Column('name', String(64), unique = True)
)
SchoolMapLocTopic_t = Table('schoolMapLocTopics', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('user_id', BigInteger, ForeignKey('users.id')),
Column('schoolMapLoc_id', BigInteger, ForeignKey('schoolMapLocs.id')),
Column('createTime', DateTime(timezone = True), index = True),
Column('updateTime', DateTime(timezone = True), index = True),
Column('postCount', Integer, index = True),
Column('title', Text),
Column('content', Text),
)
SchoolMapLocTopicPost_t = Table('schoolMapLocTopicPosts', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('user_id', BigInteger, ForeignKey('users.id')),
Column('createTime', DateTime(timezone = True), index = True),
Column('updateTime', DateTime(timezone = True), index = True),
Column('content', Text),
Column('topic_id', BigInteger, ForeignKey('schoolMapLocTopics.id')),
)
SchoolMapPiece_t = Table('schoolMapPieces', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('posX', Integer, index = True),
Column('posY', Integer, index = True),
Column('width', Integer),
Column('height', Integer),
Column('filename', String(256)),
Column('schoolMap_id', Integer, ForeignKey('schoolMapsDefault.id'))
)
SchoolType_t = Table('schoolTypes', Base.metadata,
Column('id', Integer, primary_key = True),
Column('name', String(64), unique = True)
)
Store_t = Table('stores', Base.metadata,
Column('id', BigInteger, ForeignKey('schoolMapLocs.id'), primary_key = True)
)
SchoolMapLoc_SchoolMapLocType_t = Table('schoolMapLocs_schoolMapLocTypes', Base.metadata,
Column('schoolMapLoc_id', BigInteger, ForeignKey('schoolMapLocs.id'), primary_key = True),
Column('schoolMapLocType_id', Integer, ForeignKey('schoolMapLocTypes.id'), primary_key = True)
)
SchoolMapDefault_SchoolMapLoc_t = Table('schoolMapsDefault_schoolMapLocs', Base.metadata,
Column('schoolMapDefualt_id', Integer, ForeignKey('schoolMapsDefault.id'), primary_key = True),
Column('schoolMapLoc_id', BigInteger, ForeignKey('schoolMapLocs.id'), primary_key = True),
Column('posX', Integer),
Column('posY', Integer)
)
SchoolMapGoogle_SchoolMapLoc_t = Table('schoolMapsGoogle_schoolMapLocs', Base.metadata,
Column('schoolMapGoogle_id', Integer, ForeignKey('schoolMapsGoogle.id'), primary_key = True),
Column('schoolMapLoc_id', BigInteger, ForeignKey('schoolMapLocs.id'), primary_key = True),
Column('posX', Numeric(precision = 16, scale = 12)),
Column('posY', Numeric(precision = 16, scale = 12))
)
Discount_User_t = Table('discounts_users', Base.metadata,
Column('discount_id', Integer, ForeignKey('discounts.id'), primary_key = True),
Column('user_id', BigInteger, ForeignKey('users.id'), primary_key = True),
Column('type', ENUM('like', 'dislike'), index = True),
Column('createTime', DateTime(timezone = True), index = True),
)
School_User_t = Table('schools_users', Base.metadata,
Column('school_id', Integer, ForeignKey('schools.id'), primary_key = True),
Column('user_id', BigInteger, ForeignKey('users.id'), primary_key = True),
Column('profession_id', Integer, ForeignKey('professions.id')),
Column('grade', Integer, index = True)
)
SchoolMapLoc_User_t = Table('schoolMapLocs_users', Base.metadata,
Column('schoolMapLoc_id', BigInteger, ForeignKey('schoolMapLocs.id'), primary_key = True),
Column('user_id', BigInteger, ForeignKey('users.id'), primary_key = True),
Column('rating', SmallInteger, index = True),
Column('visitCount', Integer, index = True)
)
class CardSeller(object) :
def __init__(self, schoolMapLoc_id) :
self.id = schoolMapLoc_id
class Discount(object) :
def __init__(self, name, validTime, expireTime, largePic, smallPic, store_id) :
self.name = name
self.createTime = datetime.datetime.now()
self.validTime = validTime
self.expireTime = expireTime
self.largePic = largePic
self.smallPic = smallPic
self.store_id = store_id
class School(object) :
def __init__(self, name, type_id, city_id) :
self.name = name
self.type_id = type_id
self.city_id = city_id
class SchoolMap(object) :
def __init__(self, name, school_id) :
self.name = name
self.school_id = school_id
class SchoolMapDefault(object) :
def __init__(self, schoolMap_id, width, height) :
self.id = schoolMap_id
self.width = width
self.height = height
class SchoolMapGoogle(object) :
def __init__(self, schoolMap_id, zoom, posX, posY) :
self.id = schoolMap_id
self.zoom = zoom
self.posX = posX
self.posY = posY
class SchoolMapLoc(object) :
def __init__(self, name, address, description) :
self.name = name
self.address = address
self.updateTime = datetime.datetime.now()
self.avgRating = 0.0
self.visitCount = 0
self.topicCount = 0
self.ranking = 0.0
self.description = description
class SchoolMapLocTopic(object) :
def __init__(self, user_id, schoolMapLoc_id, title, content) :
self.user_id = user_id
self.schoolMapLoc_id = schoolMapLoc_id
self.createTime = datetime.datetime.now()
self.updateTime = datetime.datetime.now()
self.title = title
self.content = content
self.postCount = 0
class SchoolMapLocTopicPost(object) :
def __init__(self, user_id, content, topic_id) :
self.user_id = user_id
self.createTime = datetime.datetime.now()
self.updateTime = datetime.datetime.now()
self.content = content
self.topic_id = topic_id
class SchoolMapLocPic(object) :
def __init__(self, schoolMapLoc_id, smallPic, largePic, picCode) :
self.schoolMapLoc_id = schoolMapLoc_id
self.smallPic = smallPic
self.largePic = largePic
self.createTime = datetime.datetime.now()
self.picCode = picCode
class SchoolMapLocType(object) :
def __init__(self, name) :
self.name = name
class SchoolMapPiece(object) :
def __init__(self, posX, posY, width, height, filename, schoolMap_id) :
self.posX = posX
self.posY = posY
self.width = width
self.height = height
self.filename = filename
self.schoolMap_id = schoolMap_id
class SchoolType(object) :
def __init__(self, name) :
self.name = name
class Store(object) :
def __init__(self, id) :
self.id = id
class SchoolMapDefault_SchoolMapLoc(object) :
def __init__(self, schoolMapDefault_id, schoolMapLoc_id, posX, posY) :
self.schoolMapDefault_id = schoolMapDefault_id
self.schoolMapLoc_id = schoolMapLoc_id
self.posX = posX
self.posY = posY
class SchoolMapGoogle_SchoolMapLoc(object) :
def __init__(self, schoolMapGoogle_id, schoolMapLoc_id, posX, posY) :
self.schoolMapGoogle_id = schoolMapGoogle_id
self.schoolMapLoc_id = schoolMapLoc_id
self.posX = posX
self.posY = posY
class SchoolMapLoc_SchoolMapLocType(object) :
def __init__(self, schoolMapLoc_id, schoolMapLocType_id) :
self.schoolMapLoc_id = schoolMapLoc_id
self.schoolMapLocType_id = schoolMapLocType_id
class Discount_User(object) :
def __init__(self, discount_id, user_id, like) :
self.discount_id = discount_id
self.user_id = user_id
self.like = like
class School_User(object) :
def __init__(self, school_id, user_id, profession_id, grade) :
self.school_id = school_id
self.user_id = user_id
self.profession_id = profession_id
self.grade = grade
class SchoolMapLoc_User(object) :
def __init__(self, schoolMapLoc_id, user_id, rating) :
self.schoolMapLoc_id = schoolMapLoc_id
self.user_id = user_id
self.rating = rating
self.visitCount = 0
from fidoweb.model.user import User, CardApplication
mapper(CardSeller, CardSeller_t, properties = {
'id' : CardSeller_t.c.id,
'mapLoc' : relation(SchoolMapLoc, backref = 'cardSeller'),
'applications' : relation(CardApplication, backref = 'seller')
})
mapper(Discount, Discount_t, properties = {
'id' : Discount_t.c.id,
'name' : Discount_t.c.name,
'createTime' : Discount_t.c.createTime,
'validTime' : Discount_t.c.validTime,
'expireTime' : Discount_t.c.expireTime,
'largePic' : Discount_t.c.largePic,
'smallPic' : Discount_t.c.smallPic,
'store_id' : Discount_t.c.store_id,
'users' : relation(User, secondary = Discount_User_t, backref = 'discounts'),
})
mapper(School, School_t, properties = {
'id' : School_t.c.id,
'name' : School_t.c.name,
'type_id' : School_t.c.type_id,
'city_id' : School_t.c.city_id,
'maps' : relation(SchoolMap, backref = 'school'),
'users' : relation(User, secondary = School_User_t, backref = 'schools'),
})
mapper(SchoolMap, SchoolMap_t, properties = {
'id' : SchoolMap_t.c.id,
'name' : SchoolMap_t.c.name,
'school_id' : SchoolMap_t.c.school_id,
'defaultMap' : relation(SchoolMapDefault, backref = 'schoolMap'),
'googleMap' : relation(SchoolMapGoogle, backref = 'schoolMap')
})
mapper(SchoolMapDefault, SchoolMapDefault_t, properties = {
'id' : SchoolMapDefault_t.c.id,
'width' : SchoolMapDefault_t.c.width,
'height' : SchoolMapDefault_t.c.height,
'mapPieces' : relation(SchoolMapPiece, backref = 'map'),
'mapLocs' : relation(SchoolMapLoc, secondary = SchoolMapDefault_SchoolMapLoc_t, backref = 'defaultMaps', order_by = SchoolMapLoc_t.c.ranking.desc())
})
mapper(SchoolMapGoogle, SchoolMapGoogle_t, properties = {
'id' : SchoolMapGoogle_t.c.id,
'zoom' : SchoolMapGoogle_t.c.zoom,
'posX' : SchoolMapGoogle_t.c.posX,
'posY' : SchoolMapGoogle_t.c.posY,
'mapLocs' : relation(SchoolMapLoc, secondary = SchoolMapGoogle_SchoolMapLoc_t, backref = 'googleMaps', order_by = SchoolMapLoc_t.c.ranking.desc())
})
mapper(SchoolMapLoc, SchoolMapLoc_t, properties = {
'id' : SchoolMapLoc_t.c.id,
'address' : SchoolMapLoc_t.c.address,
'name' : SchoolMapLoc_t.c.name,
'updateTime' : SchoolMapLoc_t.c.updateTime,
'visitCount' : SchoolMapLoc_t.c.visitCount,
'avgRating' : SchoolMapLoc_t.c.avgRating,
'topicCount' : SchoolMapLoc_t.c.topicCount,
'ranking' : SchoolMapLoc_t.c.ranking,
'description' : SchoolMapLoc_t.c.description,
'types' : relation(SchoolMapLocType, secondary = SchoolMapLoc_SchoolMapLocType_t, backref = 'mapLocs'),
'pics' : relation(SchoolMapLocPic, backref = 'mapLoc'),
'users' : relation(User, secondary = SchoolMapLoc_User_t, backref = 'schoolMapLocs'),
'topics' : relation(SchoolMapLocTopic, backref = 'mapLoc'),
'store' : relation(Store, uselist = False, backref = 'mapLoc'),
})
mapper(SchoolMapLocTopic, SchoolMapLocTopic_t, properties = {
'id' : SchoolMapLocTopic_t.c.id,
'user_id' : SchoolMapLocTopic_t.c.user_id,
'schoolMapLoc_id' : SchoolMapLocTopic_t.c.schoolMapLoc_id,
'createTime' : SchoolMapLocTopic_t.c.createTime,
'updateTime' : SchoolMapLocTopic_t.c.updateTime,
'title' : SchoolMapLocTopic_t.c.title,
'content' : SchoolMapLocTopic_t.c.content,
'postCount' : SchoolMapLocTopic_t.c.postCount,
'posts' : relation(SchoolMapLocTopicPost, backref = 'topic'),
})
mapper(SchoolMapLocTopicPost, SchoolMapLocTopicPost_t, properties = {
'id' : SchoolMapLocTopicPost_t.c.id,
'user_id' : SchoolMapLocTopicPost_t.c.user_id,
'createTime' : SchoolMapLocTopicPost_t.c.createTime,
'updateTime' : SchoolMapLocTopicPost_t.c.updateTime,
'content' : SchoolMapLocTopicPost_t.c.content,
'topic_id' : SchoolMapLocTopicPost_t.c.topic_id,
})
mapper(SchoolMapLocPic, SchoolMapLocPic_t, properties = {
'id' : SchoolMapLocPic_t.c.id,
'schoolMapLoc_id' : SchoolMapLocPic_t.c.schoolMapLoc_id,
'picCode' : SchoolMapLocPic_t.c.picCode,
'createTime' : SchoolMapLocPic_t.c.createTime,
'smallPic' : SchoolMapLocPic_t.c.smallPic,
'largePic' : SchoolMapLocPic_t.c.largePic
})
mapper(SchoolMapLocType, SchoolMapLocType_t, properties = {
'id' : SchoolMapLocType_t.c.id,
'name' : SchoolMapLocType_t.c.name,
})
mapper(SchoolMapPiece, SchoolMapPiece_t, properties = {
'id' : SchoolMapPiece_t.c.id,
'posX' : SchoolMapPiece_t.c.posX,
'posY' : SchoolMapPiece_t.c.posY,
'width' : SchoolMapPiece_t.c.width,
'height' : SchoolMapPiece_t.c.height,
'filename' : SchoolMapPiece_t.c.filename,
'schoolMap_id' : SchoolMapPiece_t.c.schoolMap_id,
})
mapper(SchoolType, SchoolType_t, properties = {
'id' : SchoolType_t.c.id,
'name' : SchoolType_t.c.name,
'schools' : relation(School, backref = 'type'),
})
mapper(Store, Store_t, properties = {
'id' : Store_t.c.id,
'discounts' : relation(Discount, backref = 'store'),
})
mapper(SchoolMapDefault_SchoolMapLoc, SchoolMapDefault_SchoolMapLoc_t, properties = {
'schoolMapDefualt_id' : SchoolMapDefault_SchoolMapLoc_t.c.schoolMapDefualt_id,
'schoolMapLoc_id' : SchoolMapDefault_SchoolMapLoc_t.c.schoolMapLoc_id,
'posX' : SchoolMapDefault_SchoolMapLoc_t.c.posX,
'posY' : SchoolMapDefault_SchoolMapLoc_t.c.posY,
})
mapper(SchoolMapGoogle_SchoolMapLoc, SchoolMapGoogle_SchoolMapLoc_t, properties = {
'schoolMapGoogle_id' : SchoolMapGoogle_SchoolMapLoc_t.c.schoolMapGoogle_id,
'schoolMapLoc_id' : SchoolMapGoogle_SchoolMapLoc_t.c.schoolMapLoc_id,
'posX' : SchoolMapGoogle_SchoolMapLoc_t.c.posX,
'posY' : SchoolMapGoogle_SchoolMapLoc_t.c.posY,
})
mapper(SchoolMapLoc_SchoolMapLocType, SchoolMapLoc_SchoolMapLocType_t, properties = {
'schoolMapLoc_id' : SchoolMapLoc_SchoolMapLocType_t.c.schoolMapLoc_id,
'schoolMapLocType_id' : SchoolMapLoc_SchoolMapLocType_t.c.schoolMapLocType_id,
})
mapper(Discount_User, Discount_User_t, properties = {
'discount_id' : Discount_User_t.c.discount_id,
'user_id' : Discount_User_t.c.user_id,
'type' : Discount_User_t.c.type,
'createTime' : Discount_User_t.c.createTime,
})
mapper(School_User, School_User_t, properties = {
'school_id' : School_User_t.c.school_id,
'user_id' : School_User_t.c.user_id,
'profession_id' : School_User_t.c.profession_id,
'grade' : School_User_t.c.grade,
})
mapper(SchoolMapLoc_User, SchoolMapLoc_User_t, properties = {
'schoolMapLoc_id' : SchoolMapLoc_User_t.c.schoolMapLoc_id,
'user_id' : SchoolMapLoc_User_t.c.user_id,
'rating' : SchoolMapLoc_User_t.c.rating,
'visitCount' : SchoolMapLoc_User_t.c.visitCount
})
| Python |
import datetime
from sqlalchemy import Table, Column, ForeignKey
from sqlalchemy.orm import relation, backref, mapper
from sqlalchemy.types import BigInteger, Integer, String, DateTime, Text, Boolean, Date
from sqlalchemy.dialects.mysql import ENUM
from fidoweb.model.meta import Base
"""
Rules
1. Tables and Inner relations are sorted in alphabet order, and Inner relations are defined after Tables
2. About relations:
For m-m and o-o relations: 'relation' defined in the first element of the relation
For o-m(m-o) relations: 'relation' defined in the element of 'm' side
"""
"""
Tables
Media139Mail
Media139MailTrialUser
Media139MailType
"""
"""
Inner relations
Media139Mail(type) o-m Media139MailType(mails)
"""
"""
Outer relations
Media139MailTypes(users) m-m User(media139MailTypes) (Describing whether a user need a certain kind of Fido Media)
Media139MailTrialUser(user) o-o User(media139MailTrialUser)
"""
Media139Mail_t = Table('media139Mails', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('createTime', DateTime, index = True),
Column('content', Text),
Column('type_id', Integer, ForeignKey('media139MailTypes.id'), index = True),
)
Media139MailTrialUser_t = Table('media139MailTrialUsers', Base.metadata,
Column('id', BigInteger, ForeignKey('users.id'), primary_key = True),
)
Media139MailType_t = Table('media139MailTypes', Base.metadata,
Column('id', Integer, primary_key = True),
Column('name', String(64), unique = True),
)
Media139MailType_User_t = Table('media139MailTypes_users', Base.metadata,
Column('media139MailType_id', Integer, ForeignKey('media139MailTypes.id'), primary_key = True),
Column('user_id', BigInteger, ForeignKey('users.id'), primary_key = True),
Column('createTime', DateTime(timezone = True), index = True),
)
class Media139Mail(object) :
def __init__(self, content, type_id) :
self.createTime = datetime.datetime.now()
self.content = content
self.type_id = type_id
class Media139MailTrialUser(object) :
def __init__(self, user_id) :
self.id = user_id
class Media139MailType(object) :
def __init__(self, name) :
self.name = name
class Media139MailType_User(object) :
def __init__(self, media139MailType_id, user_id) :
self.media139MailType_id = media139MailType_id
self.user_id = user_id
self.createTime = datetime.datetime.now()
from fidoweb.model.user import User
mapper(Media139Mail, Media139Mail_t, properties = {
'id' : Media139Mail_t.c.id,
'createTime' : Media139Mail_t.c.createTime,
'content' : Media139Mail_t.c.content,
'type_id' : Media139Mail_t.c.type_id,
})
mapper(Media139MailTrialUser, Media139MailTrialUser_t, properties = {
'id' : Media139MailTrialUser_t.c.id,
'user' : relation(User, backref = 'media139MailTrialUser'),
})
mapper(Media139MailType, Media139MailType_t, properties = {
'id' : Media139MailType_t.c.id,
'name' : Media139MailType_t.c.name,
'mails' : relation(Media139Mail, backref = 'type'),
'users' : relation(User, secondary = Media139MailType_User_t, backref = 'media139MailTypes')
})
mapper(Media139MailType_User, Media139MailType_User_t, properties = {
'media139MailType_id' : Media139MailType_User_t.c.media139MailType_id,
'user_id' : Media139MailType_User_t.c.user_id,
'createTime' : Media139MailType_User_t.c.createTime
}) | Python |
"""SQLAlchemy Metadata and Session object"""
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
__all__ = ['Base', 'Session']
# SQLAlchemy session manager. Updated by model.init_model()
Session = scoped_session(sessionmaker())
# The declarative Base
Base = declarative_base()
| Python |
"""The application's model objects"""
from fidoweb.model.meta import Session, Base
from fidoweb.model.homepageGalleryPic import *
from fidoweb.model.map import *
from fidoweb.model.user import *
from fidoweb.model.locate import *
from fidoweb.model.media import *
from fidoweb.model.group import *
def init_model(engine) :
"""Call me before using any of the tables or classes in the model"""
Session.configure(bind = engine)
| Python |
from sqlalchemy import Table, Column, ForeignKey
from sqlalchemy.orm import relation, backref
from sqlalchemy.types import BigInteger, Integer, String, DateTime, Text
from fidoweb.model.meta import Base
from fidoweb.model.locate import City
| Python |
import datetime
from sqlalchemy import Table, Column, ForeignKey
from sqlalchemy.orm import relation, backref, mapper
from sqlalchemy.types import BigInteger, Integer, String, DateTime, Text, Float, Boolean
from fidoweb.model.meta import Base
"""
Rules
1. Tables and Inner relations are sorted in alphabet order, and Inner relations are defined after Tables
2. About relations:
For m-m and o-o relations: 'relation' defined in the first element of the relation
For o-m(m-o) relations: 'relation' defined in the element of 'm' side
"""
"""
Tables
Group
GroupTopic
GroupTopicPost
Tag
TagType
"""
"""
Inner relations
Group(topics) o-m GroupTopic(group)
Group(tags) m-m Tag(groups)
GroupTopic(posts) o-m GroupTopicPost(topic)
Tag(type) m-o TagType(tags)
"""
"""
Outer relations
Group(founder) m-o User(foundedGroups)
Group(admins) m-m User(adminGroups) (describing the administrators of a group)
Group(users) m-m User(groups) (describing whether a user is in a group)
Group(schools) m-m School(groups) (describing whether a group is in certain school)
GroupTopic(user) m-o User(groupTopics)
GroupTopicPost(user) m-o User(groupTopicPosts)
"""
Group_t = Table('groups', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('name', String(64), index = True),
Column('description', Text),
Column('isAuthentic', Boolean),
Column('visitCount', BigInteger, index = True),
Column('userCount', Integer, index = True),
Column('topicCount', Integer, index = True),
Column('founder_id', BigInteger, ForeignKey('users.id')),
Column('ranking', Float, index = True),
Column('createTime', DateTime(timezone = True), index = True),
Column('updateTime', DateTime(timezone = True), index = True)
)
GroupTopic_t = Table('groupTopics', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('title', Text),
Column('content', Text),
Column('postCount', Integer, index = True),
Column('createTime', DateTime(timezone = True), index = True),
Column('updateTime', DateTime(timezone = True), index = True),
Column('user_id', BigInteger, ForeignKey('users.id')),
Column('group_id', BigInteger, ForeignKey('groups.id')),
Column('isTopped', Boolean, index = True)
)
GroupTopicPost_t = Table('groupTopicPosts', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('user_id', BigInteger, ForeignKey('users.id')),
Column('createTime', DateTime(timezone = True), index = True),
Column('updateTime', DateTime(timezone = True), index = True),
Column('content', Text),
Column('topic_id', BigInteger, ForeignKey('groupTopics.id'))
)
Tag_t = Table('tags', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('type_id', ForeignKey('tagTypes.id')),
Column('name', String(64), index = True)
)
TagType_t = Table('tagTypes', Base.metadata,
Column('id', BigInteger, primary_key = True),
Column('name', String(64), unique = True)
)
Group_School_t = Table('groups_schools', Base.metadata,
Column('group_id', BigInteger, ForeignKey('groups.id'), primary_key = True),
Column('school_id', Integer, ForeignKey('schools.id'), primary_key = True),
Column('createTime', DateTime(timezone = True), index = True)
)
Group_User_t = Table('groups_users', Base.metadata,
Column('group_id', BigInteger, ForeignKey('groups.id'), primary_key = True),
Column('user_id', BigInteger, ForeignKey('users.id'), primary_key = True),
Column('createTime', DateTime(timezone = True), index = True),
Column('updateTime', DateTime(timezone = True), index = True),
Column('visitCount', BigInteger, index = True)
)
Group_Tag_t = Table('groups_tags', Base.metadata,
Column('group_id', BigInteger, ForeignKey('groups.id'), primary_key = True),
Column('tag_id', BigInteger, ForeignKey('tags.id'), primary_key = True)
)
Group_User_Management_t = Table('groups_users_management', Base.metadata,
Column('group_id', BigInteger, ForeignKey('groups.id'), primary_key = True),
Column('user_id', BigInteger, ForeignKey('users.id'), primary_key = True),
Column('createTime', DateTime(timezone = True), index = True)
)
class Group(object) :
def __init__(self, name, description, founder_id) :
self.name = name
self.description = description
self.isAuthentic = False
self.visitCount = 0
self.userCount = 1
self.topicCount = 0
self.founder_id = founder_id
self.ranking = 0
self.createTime = datetime.datetime.now()
self.updateTime = datetime.datetime.now()
class GroupTopic(object) :
def __init__(self, title, content, user_id, group_id) :
self.title = title
self.content = content
self.postCount = 0
self.createTime = datetime.datetime.now()
self.updateTime = datetime.datetime.now()
self.user_id = user_id
self.group_id = group_id
self.isTopped = False
class GroupTopicPost(object) :
def __init__(self, content, user_id, topic_id) :
self.content = content
self.user_id = user_id
self.group_id = group_id
self.createTime = datetime.datetime.now()
self.updateTime = datetime.datetime.now()
class Tag(object) :
def __init__(self, name, type_id) :
self.name = name
self.type_id = type_id
class TagType(object) :
def __init__(self, name) :
self.name = name
class Group_School(object) :
def __init__(self, group_id, school_id) :
self.group_id = group_id
self.school_id = school_id
self.createTime = datetime.datetime.now()
class Group_User(object) :
def __init__(self, group_id, user_id, visitCount) :
self.group_id = group_id
self.user_id = user_id
self.visitCount = visitCount
self.createTime = datetime.datetime.now()
self.updateTime = datetime.datetime.now()
class Group_Tag(object) :
def __init__(self, group_id, tag_id) :
self.group_id = group_id
self.tag_id = tag_id
class Group_User_Management(object) :
def __init__(self, group_id, user_id) :
self.group_id = group_id
self.user_id = user_id
self.createTime = datetime.datetime.now()
from fidoweb.model.user import User
from fidoweb.model.map import School
mapper(Group, Group_t, properties = {
'id' : Group_t.c.id,
'name' : Group_t.c.name,
'description' : Group_t.c.description,
'isAuthentic' : Group_t.c.isAuthentic,
'visitCount' : Group_t.c.visitCount,
'userCount' : Group_t.c.userCount,
'topicCount' : Group_t.c.topicCount,
'ranking' : Group_t.c.ranking,
'createTime' : Group_t.c.createTime,
'updateTime' : Group_t.c.updateTime,
'founder ' : relation(User, backref = 'foundedGroups'),
'users' : relation(User, secondary = Group_User_t, backref = 'groups'),
'tags' : relation(Tag, secondary = Group_Tag_t, backref = 'groups'),
'admins' : relation(User, secondary = Group_User_Management_t, backref = 'adminGroups'),
'schools' : relation(School, secondary = Group_School_t, backref = 'groups')
})
mapper(GroupTopic, GroupTopic_t, properties = {
'id' : GroupTopic_t.c.id,
'title' : GroupTopic_t.c.title,
'content' : GroupTopic_t.c.content,
'postCount' : GroupTopic_t.c.postCount,
'createTime' : GroupTopic_t.c.createTime,
'updateTime' : GroupTopic_t.c.updateTime,
'isTopped' : GroupTopic_t.c.isTopped,
'user' : relation(User, backref = 'groupTopics'),
'group' : relation(Group, backref = 'topics')
})
mapper(GroupTopicPost, GroupTopicPost_t, properties = {
'id' : GroupTopicPost_t.c.id,
'createTime' : GroupTopicPost_t.c.createTime,
'updateTime' : GroupTopicPost_t.c.updateTime,
'content' : GroupTopicPost_t.c.content,
'user' : relation(User, backref = 'groupTopicPosts'),
'groupTopic' : relation(GroupTopic, backref = 'posts')
})
mapper(Tag, Tag_t, properties = {
'id' : Tag_t.c.id,
'name' : Tag_t.c.name,
'type' : relation(TagType, backref = 'tags')
})
mapper(TagType, TagType_t, properties = {
'id' : TagType_t.c.id,
'name' : TagType_t.c.name
})
mapper(Group_School, Group_School_t, properties = {
'group_id' : Group_School_t.c.group_id,
'school_id' : Group_School_t.c.school_id,
'createTime' : Group_School_t.c.createTime
})
mapper(Group_User, Group_User_t, properties = {
'group_id' : Group_User_t.c.group_id,
'user_id' : Group_User_t.c.user_id,
'createTime' : Group_User_t.c.createTime,
'updateTime' : Group_User_t.c.updateTime,
'visitCount' : Group_User_t.c.visitCount
})
mapper(Group_Tag, Group_Tag_t, properties = {
'group_id' : Group_Tag_t.c.group_id,
'tag_id' : Group_Tag_t.c.tag_id
})
mapper(Group_User_Management, Group_User_Management_t, properties = {
'group_id' : Group_User_Management_t.c.group_id,
'user_id' : Group_User_Management_t.c.user_id,
'createTime' : Group_User_Management_t.c.createTime
})
| Python |
from sqlalchemy import Table, Column, ForeignKey
from sqlalchemy.orm import relation, backref
from sqlalchemy.types import BigInteger, Integer, String
from fidoweb.model.meta import Base
from fidoweb.model.locate import City
from fidoweb.model.school import School
| Python |
#--
# Script to test the JavaScript hash algorithms
# This produces an HTML file, that you load in a browser to run the tests
#--
import hashlib, base64, hmac
all_algs = ['md5', 'sha1', 'ripemd160', 'sha256', 'sha512']
short = {'ripemd160': 'rmd160'}
test_strings = ['hello', 'world', u'fred\u1234'.encode('utf-8'), 'this is a longer test message to confirm that multiple blocks are handled correctly by the hashing algorithm']
print """<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"/></head><body>"""
for alg in all_algs:
algs = short.get(alg, alg)
print """<script src="%s-min.js"></script>
<script>
var pass = 0; fail = 0;
function check(a, b)
{
if(a != b)
{
document.write('Test fail: ' + a + ' != ' + b + '<br/>');
fail += 1;
}
else pass += 1;
}
document.write("Testing %s...<br/>");
""" % (alg, alg)
for t in test_strings:
h = hashlib.new(alg)
h.update(t)
print "check(hex_%s('%s'), '%s');" % (algs, t, h.hexdigest())
h = hmac.new('key', t, lambda: hashlib.new(alg))
print "check(hex_hmac_%s('key', '%s'), '%s');" % (algs, t, h.hexdigest())
print """
document.write('Tests competed - ' + pass + ' passed; ' + fail + ' failed.<br/><br/>');
</script>
"""
print "</body></html>"
| Python |
#--
# Script to test the JavaScript hash algorithms
# This produces an HTML file, that you load in a browser to run the tests
#--
import hashlib, base64, hmac
all_algs = ['md5', 'sha1', 'ripemd160', 'sha256', 'sha512']
short = {'ripemd160': 'rmd160'}
test_strings = ['hello', 'world', u'fred\u1234'.encode('utf-8'), 'this is a longer test message to confirm that multiple blocks are handled correctly by the hashing algorithm']
print """<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"/></head><body>"""
for alg in all_algs:
algs = short.get(alg, alg)
print """<script src="%s.js"></script>
<script>
var pass = 0; fail = 0;
function check(a, b)
{
if(a != b)
{
document.write('Test fail: ' + a + ' != ' + b + '<br/>');
fail += 1;
}
else pass += 1;
}
document.write("Testing %s...<br/>");
""" % (alg, alg)
for t in test_strings:
h = hashlib.new(alg)
h.update(t)
print "check(hex_%s('%s'), '%s');" % (algs, t, h.hexdigest())
print "check(b64_%s('%s'), '%s');" % (algs, t, base64.b64encode(h.digest()).rstrip('='))
h = hmac.new('key', t, lambda: hashlib.new(alg))
print "check(hex_hmac_%s('key', '%s'), '%s');" % (algs, t, h.hexdigest())
print "check(b64_hmac_%s('key', '%s'), '%s');" % (algs, t, base64.b64encode(h.digest()).rstrip('='))
print """
document.write('Tests competed - ' + pass + ' passed; ' + fail + ' failed.<br/><br/>');
</script>
"""
print "</body></html>"
| Python |
"""Pylons application test package
This package assumes the Pylons environment is already loaded, such as
when this script is imported from the `nosetests --with-pylons=test.ini`
command.
This module initializes the application via ``websetup`` (`paster
setup-app`) and provides the base testing objects.
"""
from unittest import TestCase
from paste.deploy import loadapp
from paste.script.appinstall import SetupCommand
from pylons import url
from routes.util import URLGenerator
from webtest import TestApp
import pylons.test
__all__ = ['environ', 'url', 'TestController']
# Invoke websetup with the current config file
SetupCommand('setup-app').run([pylons.test.pylonsapp.config['__file__']])
environ = {}
class TestController(TestCase):
def __init__(self, *args, **kwargs):
wsgiapp = pylons.test.pylonsapp
config = wsgiapp.config
self.app = TestApp(wsgiapp)
url._push_object(URLGenerator(config['routes.map'], environ))
TestCase.__init__(self, *args, **kwargs)
| Python |
# -*- coding: utf-8 -*-
import logging
import hashlib
import string
import json
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from fidoweb.lib.base import Session, BaseController, render
from fidoweb.lib.formChecker import FormChecker
from fidoweb.model.school import *
from fidoweb.model.user import *
from fidoweb.controllers.login import LoginController
from fidoweb.controllers.userGroup import UserGroupController
log = logging.getLogger(__name__)
"""
Authority:
Name UserGroupName Method
UserInserting Operation.HumanResource.UserManagement.UserInserting insertUser
"""
class OaController(BaseController) :
_authority = {
'UserInserting' : 'Operation.HumanResource.UserManagement.Inserting'
}
def insertUser(self) :
if (not self._haveAuthority('UserInserting')) : return 'no authority'
fc = FormChecker()
if (not ('fidocard' in request.POST) or not fc.isValidFidocard(request.POST['fidocard'])) : return 'fidocard error'
if (not ('mobile' in request.POST) or not fc.isValidMobile(request.POST['mobile'])) : return 'mobile error'
if (not ('name' in request.POST) or not fc.isValidName(request.POST['name'])) : return 'name error'
if (not ('gender' in request.POST) or (request.POST['gender'] != 'male' and request.POST['gender'] != 'female')) : return 'gender error'
if (not ('birthday' in request.POST) or (fc.strToDate(request.POST['birthday']) == None)) : return 'birthday error'
if (not ('email' in request.POST) or not fc.isValidEmail(request.POST['email'])) : return 'email error'
if (not ('school' in request.POST)) : return 'school error'
else :
try :
school = int(request.POST['school'])
except :
return 'school error'
if (not ('profession' in request.POST)) : return 'profession error'
else :
try :
profession = int(request.POST['profession'])
except :
return 'profession error'
if (not ('grade' in request.POST)) : return 'grade error'
else :
try :
grade = int(request.POST['grade'])
except :
return 'grade error'
if (grade < 1900 or grade > datetime.datetime.today().year) : return 'grade error'
if (Session.query(School).filter_by(id = school).count() == 0) : return 'school error'
if (Session.query(Profession).filter_by(id = profession).count() == 0) : return 'profession error'
if (Session.query(User).filter_by(mobile = request.POST['mobile']).count() > 0) : return 'mobile registered'
if (Session.query(User).filter_by(fidocard = request.POST['fidocard']).count() > 0) : return 'fidocard registered'
if (Session.query(User).filter_by(email = request.POST['email']).count() > 0) : return 'email registered'
password = hashlib.sha512(request.POST['mobile']).hexdigest()
user = User(name = request.POST['name'], password = password, gender = request.POST['gender'],
mobile = request.POST['mobile'], birthday = fc.strToDate(request.POST['birthday']), email = request.POST['email'],
fidocard = request.POST['fidocard'])
Session.add(user)
Session.commit()
user_school = School_User(user_id = user.id, school_id = school, profession_id = profession, grade = grade)
Session.add(user_school)
Session.commit()
return 'success'
def index(self) :
lc = LoginController()
user = lc._getLoginUser()
c.title = 'OA'
c.header = render('/oa/header.mako')
if (user == None) :
c.content = '请登录。'.decode("utf8")
else :
oaUsers = Session.query(OAUser).filter_by(id = user.id)
if (oaUsers.count() == 0) :
c.content = '抱歉,您的账号没有开通OA。'.decode("utf8")
else :
c.content = render('/oa/content.mako')
return render('global/global.mako')
def _haveAuthority(self, authName) :
uc = UserGroupController()
lc = LoginController()
user = lc._getLoginUser()
if (user == None) : return False
return uc._inGroup(user, Session.query(UserGroup).filter_by(name = self._authority[authName]).first())
def getPage(self) :
if (not ('authName' in request.POST)) : return ''
authName = request.POST['authName']
if (self._haveAuthority(authName)) :
return render('/oa/page_' + string.lower(authName) + '.mako')
else :
return '抱歉,您没有访问此功能的权限。'
def getTaskList(self) :
"""
Return Format:
JSON List:
[ [Desctiption: String, Entry: String], ... ]
"""
response.headers['Content-Type'] = 'application/x-json'
ret = list()
if (self._haveAuthority('UserInserting')) : ret.append(['用户录入', 'UserInserting'])
return json.dumps(ret)
def _getOAUser(self) :
lc = LoginController()
user = lc._getLoginUser()
if (user == None) : return None
oaUsers = Session.query(OAUser).filter_by(id = user.id)
if (oaUsers.count() == 0) : return None
return oaUsers.first() | Python |
# -*- coding: utf-8 -*-
import logging
import hashlib
import string
import json
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from fidoweb.lib.base import Session, BaseController, render
from fidoweb.lib.formChecker import FormChecker
from fidoweb.model.school import *
from fidoweb.model.user import *
from fidoweb.controllers.login import LoginController
from fidoweb.controllers.userGroup import UserGroupController
log = logging.getLogger(__name__)
"""
Authority:
Name UserGroupName Method
UserInserting Operation.HumanResource.UserManagement.UserInserting insertUser
"""
class OaController(BaseController) :
_authority = {
'UserInserting' : 'Operation.HumanResource.UserManagement.Inserting'
}
def insertUser(self) :
if (not self._haveAuthority('UserInserting')) : return 'no authority'
fc = FormChecker()
if (not ('fidocard' in request.POST) or not fc.isValidFidocard(request.POST['fidocard'])) : return 'fidocard error'
if (not ('mobile' in request.POST) or not fc.isValidMobile(request.POST['mobile'])) : return 'mobile error'
if (not ('name' in request.POST) or not fc.isValidName(request.POST['name'])) : return 'name error'
if (not ('gender' in request.POST) or (request.POST['gender'] != 'male' and request.POST['gender'] != 'female')) : return 'gender error'
if (not ('birthday' in request.POST) or (fc.strToDate(request.POST['birthday']) == None)) : return 'birthday error'
if (not ('email' in request.POST) or not fc.isValidEmail(request.POST['email'])) : return 'email error'
if (not ('school' in request.POST)) : return 'school error'
else :
try :
school = int(request.POST['school'])
except :
return 'school error'
if (not ('profession' in request.POST)) : return 'profession error'
else :
try :
profession = int(request.POST['profession'])
except :
return 'profession error'
if (not ('grade' in request.POST)) : return 'grade error'
else :
try :
grade = int(request.POST['grade'])
except :
return 'grade error'
if (grade < 1900 or grade > datetime.datetime.today().year) : return 'grade error'
if (Session.query(School).filter_by(id = school).count() == 0) : return 'school error'
if (Session.query(Profession).filter_by(id = profession).count() == 0) : return 'profession error'
if (Session.query(User).filter_by(mobile = request.POST['mobile']).count() > 0) : return 'mobile registered'
if (Session.query(User).filter_by(fidocard = request.POST['fidocard']).count() > 0) : return 'fidocard registered'
if (Session.query(User).filter_by(email = request.POST['email']).count() > 0) : return 'email registered'
password = hashlib.sha512(request.POST['mobile']).hexdigest()
user = User(name = request.POST['name'], password = password, gender = request.POST['gender'],
mobile = request.POST['mobile'], birthday = fc.strToDate(request.POST['birthday']), email = request.POST['email'],
fidocard = request.POST['fidocard'])
Session.add(user)
Session.commit()
user_school = School_User(user_id = user.id, school_id = school, profession_id = profession, grade = grade)
Session.add(user_school)
Session.commit()
return 'success'
def index(self) :
lc = LoginController()
user = lc._getLoginUser()
c.title = 'OA'
c.header = render('/oa/header.mako')
if (user == None) :
c.content = '请登录。'.decode("utf8")
else :
oaUsers = Session.query(OAUser).filter_by(id = user.id)
if (oaUsers.count() == 0) :
c.content = '抱歉,您的账号没有开通OA。'.decode("utf8")
else :
c.content = render('/oa/content.mako')
return render('global/global.mako')
def _haveAuthority(self, authName) :
uc = UserGroupController()
lc = LoginController()
user = lc._getLoginUser()
if (user == None) : return False
return uc._inGroup(user, Session.query(UserGroup).filter_by(name = self._authority[authName]).first())
def getPage(self) :
if (not ('authName' in request.POST)) : return ''
authName = request.POST['authName']
if (self._haveAuthority(authName)) :
return render('/oa/page_' + string.lower(authName) + '.mako')
else :
return '抱歉,您没有访问此功能的权限。'.decode("utf8")
def getTaskList(self) :
"""
Return Format:
JSON List:
[ [Desctiption: String, Entry: String], ... ]
"""
response.headers['Content-Type'] = 'application/x-json'
ret = list()
if (self._haveAuthority('UserInserting')) : ret.append(['用户录入'.decode('utf8'), 'UserInserting'])
return json.dumps(ret)
def _getOAUserId(self) :
lc = LoginController()
user = lc._getLoginUser()
if (user == None) : return None
oaUsers = Session.query(OAUser).filter_by(id = user.id)
if (oaUsers.count() == 0) : return None
return user.id | Python |
import logging
import json
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from sqlalchemy import desc
from sqlalchemy.exc import IntegrityError
from fidoweb.lib.base import Session, BaseController, render
from fidoweb.model.map import *
log = logging.getLogger(__name__)
class MapController(BaseController) :
def addSchoolMapLocComment(self) :
from fidoweb.model.map import SchoolMapLocComment
from fidoweb.controllers.login import LoginController
if ((not 'content' in request.POST) or (not 'id' in request.POST)) : return 'fail'
loc_id = request.POST['id']
content = request.POST['content']
if (len(content) == 0 or Session.query(SchoolMapLoc).filter_by(id = loc_id).count() == 0) : return 'fail'
lc = LoginController()
user = lc._getLoginUser()
if (user == None) : return 'notLoggedIn'
c = SchoolMapLocComment(user.id, loc_id, content)
Session.add(c)
Session.commit()
return 'success'
def getDiscountByStoreId(self) :
response.headers['Content-Type'] = 'application/x-json'
ret = list()
if (not 'id' in request.GET) :
return json.dumps(ret)
store_id = request.GET['id']
stores = Session.query(Store).filter_by(id = store_id)
if (stores.count() == 0) :
return json.dumps(ret)
store = stores.first()
from fidoweb.lib.algorithm import datetimeToStr
for d in store.discounts :
ret.append([d.id, d.name, datetimeToStr(d.createTime), datetimeToStr(d.validTime), datetimeToStr(d.expireTime), d.smallPic, d.largePic])
return json.dumps(ret)
def getSchoolMaps(self) :
response.headers['Content-Type'] = 'application/x-json'
ret = list()
for m in Session.query(SchoolMap) :
ret.append([m.id, m.width, m.height, m.name, m.school_id])
return json.dumps(ret)
def getSchoolMapPiecesByMapId(self) :
response.headers['Content-Type'] = 'application/x-json'
ret = list()
if (not 'id' in request.GET) :
return json.dumps(ret)
map_id = request.GET['id']
for m in Session.query(SchoolMapPiece).filter_by(schoolMap_id = map_id) :
ret.append([m.pos_x, m.pos_y, m.width, m.height, m.filename])
return json.dumps(ret)
def getSchoolMapLocComments(self) :
response.headers['Content-Type'] = 'application/x-json'
ret = list()
if ((not 'id' in request.GET)) : return json.dumps(ret)
if ((not 'start' in request.GET) or (not 'end' in request.GET)) : return json.dumps(ret)
loc_id = request.GET['id']
start = int(request.GET['start'])
end = int(request.GET['end'])
if (end - start > 20 or end - start < 0) : return json.dumps(ret)
from fidoweb.model.map import SchoolMapLocComment
comments = Session.query(SchoolMapLocComment).order_by(desc(SchoolMapLocComment.id)).filter_by(schoolMapLoc_id = loc_id).slice(start, end)
from fidoweb.lib.algorithm import datetimeToStr
for c in comments :
ret.append([c.content, datetimeToStr(c.createTime), c.user.name])
return json.dumps(ret)
def getSchoolMapLocCommentCount(self) :
response.headers['Content-Type'] = 'application/x-json'
ret = list()
if ((not 'id' in request.GET)) : return json.dumps(ret)
loc_id = request.GET['id']
ret = Session.query(SchoolMapLocComment).order_by(desc(SchoolMapLocComment.id)).filter_by(schoolMapLoc_id = loc_id).count()
return json.dumps([ret])
def getSchoolMapLocDetails(self) :
response.headers['Content-Type'] = 'application/x-json'
ret = list()
if (not 'id' in request.GET) :
return json.dumps(ret)
loc_id = request.GET['id']
for s in Session.query(SchoolMapLoc).filter_by(id = loc_id) :
likeCount = Session.query(SchoolMapLoc_User).filter_by(schoolMapLoc_id = s.id).filter_by(type = 'like').count()
dislikeCount = Session.query(SchoolMapLoc_User).filter_by(schoolMapLoc_id = s.id).filter_by(type = 'dislike').count()
commentCount = Session.query(SchoolMapLocComment).filter_by(schoolMapLoc_id = s.id).count()
ret.append([s.name, s.address, likeCount, dislikeCount, commentCount])
return json.dumps(ret)
def getSchoolMapLocsByMapId(self) :
response.headers['Content-Type'] = 'application/x-json'
ret = list()
if (not 'id' in request.GET) :
return json.dumps(ret)
map_id = request.GET['id']
maps = Session.query(SchoolMap).filter_by(id = map_id)
if (maps.count() == 0) :
return json.dumps(ret)
curMap = maps.first()
for s in curMap.mapLocs :
link = Session.query(SchoolMap_SchoolMapLoc).filter_by(schoolMap_id = curMap.id).filter_by(schoolMapLoc_id = s.id).first()
if (s.store != None) :
ret.append([s.id, link.pos_x, link.pos_y, s.name, s.address, 1])
else :
ret.append([s.id, link.pos_x, link.pos_y, s.name, s.address, 0])
return json.dumps(ret)
def getSchoolMapLocPics(self) :
response.headers['Content-Type'] = 'application/x-json'
ret = list()
if (not 'id' in request.GET) :
return json.dumps(ret)
loc_id = request.GET['id']
locs = Session.query(SchoolMapLoc).filter_by(id = loc_id)
if (locs.count() == 0) :
return json.dumps(ret)
curLoc = locs.first()
for p in curLoc.pics :
ret.append([p.type, p.filename])
return json.dumps(ret)
def getSchoolMapLocUserLike(self) :
if (not 'id' in request.POST) :
return 'error'
loc_id = request.POST['id']
from fidoweb.controllers.login import LoginController
lc = LoginController()
user = lc._getLoginUser()
if (user == None) :
return 'notLoggedIn'
suAll = Session.query(SchoolMapLoc_User).filter_by(schoolMapLoc_id = loc_id).filter_by(user_id = user.id)
if (suAll.count() == 0) :
return 'unknown'
else :
return suAll.first().type
def setSchoolMapLocUserLike(self) :
if (not ('id' in request.POST) or (not 'type' in request.POST)) :
return 'error'
loc_id = request.POST['id']
_type = request.POST['type']
if (_type != 'like' and _type != 'dislike') :
return 'error'
from fidoweb.controllers.login import LoginController
lc = LoginController()
user = lc._getLoginUser()
if (user == None) :
return 'notLoggedIn'
try :
su = SchoolMapLoc_User(loc_id, user.id, _type)
Session.add(su)
Session.commit()
except IntegrityError as e :
return 'fail'
return 'success' | Python |
import logging
import random
import datetime
import hashlib
import json
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from fidoweb.lib.base import BaseController, render, Session
from fidoweb.model.user import User, Profession
from fidoweb.model.map import School
log = logging.getLogger(__name__)
class LoginController(BaseController) :
_popupDialogs = {
'login' : '/login/popupdialog_login.mako',
}
def index(self) :
if (self._isLoggedIn()) :
c.title = 'User Panel'
c.header = render('global/globalheader.mako')
c.content = render('/login/userpanel.mako')
return render('/global/global.mako')
else :
c.title = 'Login'
c.header = render('global/globalheader.mako')
c.content = render('/login/login.mako')
return render('/global/global.mako')
def checkFidocardState(self) :
from fidoweb.model.user import User
fc = request.POST['fidocard']
users = Session.query(User).filter_by(fidocard = fc)
if (users.count() == 0) : return 'empty'
user = users.first()
if (user.websiteSignup == True) : return 'signup'
return 'not signup'
def doSignup(self) :
fidocard = request.POST['fidocard']
password = request.POST['password']
users = Session.query(User).filter_by(fidocard = fidocard)
if (users.count() == 0) : return 'fail'
user = users.first()
user.password = password
user.websiteSignup = True
Session.commit()
return 'success'
def doLogin(self) :
if (not('method' in request.POST) or not ('username' in request.POST) or not ('password' in request.POST)) :
return 'fail'
if (request.POST['method'] == 'mobile') :
users = Session.query(User).filter_by(mobile = request.POST['username'])
else :
users = Session.query(User).filter_by(fidocard = request.POST['username'])
password = request.POST['password']
if (users.count() == 0) : return 'wrong username'
user = users.first()
if (('loginCode' in session) and ('loginCodeGeneratingTime' in session) and (datetime.datetime.now() - session['loginCodeGeneratingTime']).seconds < 20) :
p = hashlib.sha512(session['loginCode'] + user.password).hexdigest()
if (p == password) :
session['mobile'] = user.mobile
session['loggedIn'] = True
session.save()
return 'success'
else :
return 'wrong password'
return 'fail'
def getLoginCode(self) :
res = ''
for i in range(0, 20) :
res += chr(random.randint(48, 122))
session['loginCode'] = res
session['loginCodeGeneratingTime'] = datetime.datetime.now()
session.save()
return res
def getSchools(self) :
response.headers['Content-Type'] = 'application/x-json'
ret = list()
for school in Session.query(School) :
ret.append([school.id, school.name.decode('utf8')])
return json.dumps(ret)
def getProfessions(self) :
response.headers['Content-Type'] = 'application/x-json'
ret = list()
for pro in Session.query(Profession) :
ret.append([pro.id, pro.name.decode('utf8')])
return json.dumps(ret)
def getPopupDialog(self) :
if (not 'name' in request.POST) : return ''
name = request.POST['name']
if (self._popupDialogs.get(name) == None) :
return ''
else :
return render(self._popupDialogs[name])
def getLoginUser(self) :
response.headers['Content-Type'] = 'application/x-json'
ret = list()
user = self._getLoginUser()
if (user == None) :
return json.dumps(ret)
ret.append(user.name)
ret.append(user.gender)
ret.append(user.mobile)
from fidoweb.lib.algorithm import dateToStr
ret.append(dateToStr(user.birthday))
ret.append(user.fidoPoints)
ret.append(user.email)
ret.append(user.fidocard)
return json.dumps(ret)
def getUserSchoolMapLocLikeCount(self) :
response.headers['Content-Type'] = 'application/x-json'
if ((not 'type' in request.GET) or (request.GET['type'] != 'like' and request.GET['type'] != 'dislike') and request.GET['type'] != 'all') :
return ''
like_type = request.GET['type']
user = self._getLoginUser()
if (user == None) : return ''
from fidoweb.model.map import SchoolMapLoc_User
if (like_type == 'all') :
ret = Session.query(SchoolMapLoc_User).filter_by(user_id = user.id).count()
else :
ret = Session.query(SchoolMapLoc_User).filter_by(user_id = user.id).filter_by(type = like_type).count()
return json.dumps([ret])
def getUserSchoolMapLocLike(self) :
response.headers['Content-Type'] = 'application/x-json'
ret = list()
if ((not 'type' in request.GET) or (request.GET['type'] != 'like' and request.GET['type'] != 'dislike') and request.GET['type'] != 'all') :
return json.dumps(ret)
if ((not 'start' in request.GET) or (not 'end' in request.GET)) :
return json.dumps(ret)
like_type = request.GET['type']
start = int(request.GET['start'])
end = int(request.GET['end'])
if (end - start > 20 or end - start < 0) :
return json.dumps(ret)
user = self._getLoginUser()
if (user == None) :
return json.dumps(ret)
from fidoweb.model.map import SchoolMapLoc, SchoolMapLoc_User
if (like_type == 'all') :
userLocs = Session.query(SchoolMapLoc_User).filter_by(user_id = user.id).slice(start, end)
else :
userLocs = Session.query(SchoolMapLoc_User).filter_by(user_id = user.id).filter_by(type = like_type).slice(start, end)
for userLoc in userLocs :
locs = Session.query(SchoolMapLoc).filter_by(id = userLoc.schoolMapLoc_id)
if (locs.count() == 0) : continue
loc = locs.first()
likeCount = Session.query(SchoolMapLoc_User).filter_by(schoolMapLoc_id = loc.id).filter_by(type = 'like').count()
dislikeCount = Session.query(SchoolMapLoc_User).filter_by(schoolMapLoc_id = loc.id).filter_by(type = 'dislike').count()
picList = list()
for pic in loc.pics :
picList.append([pic.type, pic.filename])
ret.append([loc.name, userLoc.type, loc.address, likeCount, dislikeCount, picList])
return json.dumps(ret)
def logout(self) :
session.clear()
session.save()
return 'success'
def signup(self) :
from fidoweb.controllers.header import HeaderController
hc = HeaderController()
c.title = 'Signup'
c.header = render('global/globalheader.mako')
c.content = render('/login/signup.mako')
return render('/global/global.mako')
def _getLoginUser(self) :
if (self._isLoggedIn()) :
users = Session.query(User).filter_by(mobile = session['mobile']);
if (users.count() > 0) :
return users.first()
else :
return None
else :
return None
def _isLoggedIn(self) :
if (('mobile' in session) and ('loggedIn' in session) and session['loggedIn'] == True) :
return True
else :
return False
| Python |
import cgi
from paste.urlparser import PkgResourcesParser
from pylons.middleware import error_document_template
from webhelpers.html.builder import literal
from fidoweb.lib.base import BaseController
class ErrorController(BaseController):
"""Generates error documents as and when they are required.
The ErrorDocuments middleware forwards to ErrorController when error
related status codes are returned from the application.
This behaviour can be altered by changing the parameters to the
ErrorDocuments middleware in your config/middleware.py file.
"""
def document(self):
"""Render the error document"""
request = self._py_object.request
resp = request.environ.get('pylons.original_response')
content = literal(resp.body) or cgi.escape(request.GET.get('message', ''))
page = error_document_template % \
dict(prefix=request.environ.get('SCRIPT_NAME', ''),
code=cgi.escape(request.GET.get('code', str(resp.status_int))),
message=content)
return page
def img(self, id):
"""Serve Pylons' stock images"""
return self._serve_file('/'.join(['media/img', id]))
def style(self, id):
"""Serve Pylons' stock stylesheets"""
return self._serve_file('/'.join(['media/style', id]))
def _serve_file(self, path):
"""Call Paste's FileApp (a WSGI application) to serve the file
at the specified path
"""
request = self._py_object.request
request.environ['PATH_INFO'] = '/%s' % path
return PkgResourcesParser('pylons', 'pylons')(request.environ, self.start_response)
| Python |
import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from fidoweb.lib.base import BaseController, render, Session
from fidoweb.model.user import User, UserGroup, User_UserGroup
log = logging.getLogger(__name__)
class UserGroupController(BaseController):
def _inGroup(self, user, userGroup) :
while (True) :
if (Session.query(User_UserGroup).filter_by(user_id = user.id).filter_by(userGroup_id = userGroup.id).count() > 0) :
return True
if (userGroup.parent_id != None) :
userGroup = Session.query(UserGroup).filter_by(id = userGroup.parent_id).first()
else :
break
return False
| Python |
import logging
import json
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from fidoweb.lib.base import Session, BaseController, render
from fidoweb.model.homepageGalleryPic import *
log = logging.getLogger(__name__)
class HomepageController(BaseController) :
_mainPages = {
'map' : '/homepage/mainpage_map.mako',
'maploc' : '/homepage/mainpage_maploc.mako',
'myloc' : '/homepage/mainpage_myloc.mako'
}
def index(self) :
c.title = 'Homepage'
c.header = ''
c.content = render('homepage/content.mako')
return render('global/global.mako')
def getLeftNavPage(self) :
from fidoweb.controllers.login import LoginController
lc = LoginController()
if (lc._isLoggedIn()) :
return render('/homepage/leftnav_loggedin.mako')
else :
return render('/homepage/leftnav_loggedout.mako')
def getMainPage(self) :
if (not 'page' in request.POST) : return ''
page = request.POST['page']
if (self._mainPages.get(page) == None) :
return ''
else :
return render(self._mainPages[page])
| Python |
# -*- coding: cp936 -*-
import logging
from sqlalchemy import or_, desc
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from fidoweb.lib.base import Session, BaseController, render
from fidoweb.lib.algorithm import checkTimeScope
log = logging.getLogger(__name__)
# Written by Hanxu, Modified by Sunzheng
class SearchController(BaseController):
def index(self) :
c.errMsg = ''
c.result = None
from fidoweb.lib.formChecker import FormChecker
fc = FormChecker()
if (not 'page' in request.GET) : c.page = 0
else :
c.page = fc.strToInt(request.GET['page'])
if (c.page == None) : c.page = 0
if ('q' in request.GET and 'type' in request.GET and len(request.GET['q']) > 0 and len(request.GET['q']) <= 30) :
c.searchType = request.GET['type']
if (not checkTimeScope('SearchController.index', 5)) : c.errMsg = 'too fast'
else :
s = request.GET['q']
words = s.split()
while (len(words) > 3) : words.pop()
if (c.searchType == '1' and len(words) > 0) :
from fidoweb.model.map import SchoolMapLoc
f = SchoolMapLoc.name.like('%' + words[0] + '%')
for i in range(1, len(words)) :
f = or_(f, SchoolMapLoc.name.like('%' + words[i] + '%'))
for i in range(0, len(words)) :
f = or_(f, SchoolMapLoc.address.like('%' + words[i] + '%'))
c.resultCount = Session.query(SchoolMapLoc).filter(f).order_by(desc(SchoolMapLoc.ranking)).count()
c.result = Session.query(SchoolMapLoc).filter(f).order_by(desc(SchoolMapLoc.ranking)).slice(c.page * 20, c.page * 20 + 20).all()
if (c.searchType == '2' and len(words) > 0) :
from fidoweb.model.map import SchoolMapLocTopic
searchStr = ''
for w in words :
w = w.replace('+', '')
w = w.replace('-', '')
searchStr = searchStr + ' *' + w + '*'
c.resultCount = Session.query(SchoolMapLocTopic).filter('MATCH (title,content) AGAINST (\'' + searchStr[1 :] + '\' IN BOOLEAN MODE)').order_by(desc(SchoolMapLocTopic.updateTime)).count()
c.result = Session.query(SchoolMapLocTopic).filter('MATCH (title,content) AGAINST (\'' + searchStr[1 :] + '\' IN BOOLEAN MODE)').order_by(desc(SchoolMapLocTopic.updateTime)).slice(c.page * 20, c.page * 20 + 20).all()
if (c.searchType == '3' and len(words) > 0) :
from fidoweb.model.map import Discount
f = Discount.name.like('%' + words[0] + '%')
for i in range(1, len(words)) :
f = or_(f, Discount.name.like('%' + words[i] + '%'))
c.resultCount = Session.query(Discount).filter(f).order_by(desc(Discount.createTime)).count()
c.result = Session.query(Discount).filter(f).order_by(desc(Discount.createTime)).slice(c.page * 20, c.page * 20 + 20).all()
else :
c.searchType = '1'
from fidoweb.controllers.login import LoginController
from fidoweb.controllers.map import MapController
lc = LoginController()
mc = MapController()
c.loginUser = lc._getLoginUser()
c.schools = mc._getSchools()
c.jsFiles = list()
c.cssFiles = list()
c.title = 'Fido - Search'
c.header = render('global/globalheader.mako')
c.content = render('search/content.mako')
return render('global/global.mako')
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.