当前位置: 首页>>代码示例>>Python>>正文


Python DrupyPHP.substr方法代码示例

本文整理汇总了Python中lib.drupy.DrupyPHP.substr方法的典型用法代码示例。如果您正苦于以下问题:Python DrupyPHP.substr方法的具体用法?Python DrupyPHP.substr怎么用?Python DrupyPHP.substr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在lib.drupy.DrupyPHP的用法示例。


在下文中一共展示了DrupyPHP.substr方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: create_filename

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import substr [as 别名]
def create_filename(basename, directory):
  """
   Create a full file path from a directory and filename + If a file with the
   specified name already exists, an alternative will be used.
  
   @param basename string filename
   @param directory string directory
   @return
  """
  dest = directory + '/' + basename
  if (php.file_exists(dest)):
    # Destination file already exists, generate an alternative.
    pos = strrpos(basename, '.')
    if (pos):
      name = php.substr(basename, 0, pos)
      ext = php.substr(basename, pos)
    else:
      name = basename
    counter = 0
    while True:
      dest = directory + '/' + name + '_' + counter + ext
      counter += 1
      if (not php.file_exists(dest)):
        break
  return dest
开发者ID:brendoncrawford,项目名称:drupy,代码行数:27,代码来源:file.py

示例2: drupal_page_cache_header

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import substr [as 别名]
def drupal_page_cache_header(cache):
    """
   Set HTTP headers in preparation for a cached page response.
  
   The general approach here is that anonymous users can keep a local
   cache of the page, but must revalidate it on every request.  Then,
   they are given a '304 Not Modified' response as long as they stay
   logged out and the page has not been modified.
  """
    # Set default values:
    last_modified = php.gmdate("D, d M Y H:i:s", cache.created) + " GMT"
    etag = '"' + drupy_md5(last_modified) + '"'
    # See if the client has provided the required HTTP headers:
    if_modified_since = (
        php.stripslashes(php.SERVER["HTTP_IF_MODIFIED_SINCE"])
        if php.isset(php.SERVER, "HTTP_IF_MODIFIED_SINCE")
        else False
    )
    if_none_match = (
        php.stripslashes(php.SERVER["HTTP_IF_NONE_MATCH"]) if php.isset(php.SERVER, "HTTP_IF_NONE_MATCH") else False
    )
    if (
        if_modified_since
        and if_none_match
        and if_none_match == etag  # etag must match
        and if_modified_since == last_modified
    ):  # if-modified-since must match
        php.header(php.SERVER["SERVER_PROTOCOL"] + " 304 Not Modified")
        # All 304 responses must send an etag if the 200 response for the same
        # object contained an etag
        php.header("Etag: %(etag)s" % {"etag": etag})
        exit()
    # Send appropriate response:
    php.header("Last-Modified: %(last_modified)s" % {"last_modified": last_modified})
    php.header("Etag: %(etag)s" % {"etag": etag})
    # The following headers force validation of cache:
    php.header("Expires: Sun, 19 Nov 1978 05:00:00 GMT")
    php.header("Cache-Control: must-revalidate")
    if variable_get("page_compression", True):
        # Determine if the browser accepts gzipped data.
        if php.strpos(php.SERVER["HTTP_ACCEPT_ENCODING"], "gzip") == False and php.function_exists("gzencode"):
            # Strip the gzip php.header and run uncompress.
            cache.data = php.gzinflate(php.substr(php.substr(cache.data, 10), 0, -8))
        elif php.function_exists("gzencode"):
            php.header("Content-Encoding: gzip")
    # Send the original request's headers. We send them one after
    # another so PHP's php.header() def can deal with duplicate
    # headers.
    headers = php.explode("\n", cache.headers)
    for php.header_ in headers:
        php.header(php.header_)
    print cache.data
开发者ID:sabren,项目名称:drupy,代码行数:54,代码来源:bootstrap.py

示例3: rewrite_sql

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import substr [as 别名]
def rewrite_sql(query, primary_table = 'n', primary_field = 'nid',  args = []):
  join_, where, distinct = _rewrite_sql(query, primary_table, \
    primary_field, args)
  if (distinct):
    query = distinct_field(primary_table, primary_field, query)
  if (not php.empty(where) or not php.empty(join_)):
    pattern = \
      '{ ' + \
      '  # Beginning of the string ' + \
      '  ^ ' + \
      '  ((?P<anonymous_view> ' + \
      '    # Everything within this set of parentheses ' + \
      '    # is named "anonymous view ' + \
      '    (?: ' + \
      '      # anything not parentheses ' + \
      '      [^()]++ ' + \
      '      | ' + \
      '      # an open parenthesis, more anonymous view and ' + \
      '      # finally a close parenthesis. ' + \
      '      \( (?P>anonymous_view) \) ' + \
      '    )* ' + \
      '  )[^()]+WHERE) ' + \
      '}X'
    matches = []
    php.preg_match(pattern, query, matches)
    if (where):
      n = php.strlen(matches[1])
      second_part = php.substr(query, n)
      first_part = php.substr(matches[1], 0, n - 5) + \
        " join WHERE where AND ( "
      # PHP 4 does not support strrpos for strings. We emulate it.
      haystack_reverse = php.strrev(second_part)
      # No need to use strrev on the needle, we supply GROUP, ORDER, LIMIT
      # reversed.
      for needle_reverse in ('PUORG', 'REDRO', 'TIMIL'):
        pos = php.strpos(haystack_reverse, needle_reverse)
        if (pos != False):
          # All needles are five characters long.
          pos += 5
          break
      if (pos == False):
        query = first_part +  second_part  + ')'
      else:
        query = first_part +  substr(second_part, 0, -pos)  + ')' + \
          php.substr(second_part, -pos)
    else:
      query = matches[1] +  " join "  + \
        php.substr(query, php.strlen(matches[1]))
  return query
开发者ID:brendoncrawford,项目名称:drupy,代码行数:51,代码来源:database.py

示例4: connect

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import substr [as 别名]
def connect(url):
  """
   Initialise a database connection.
  
   Note that mysqli does not support persistent connections.
  """
  # Check if MySQLi support is present in PHP
  url = php.parse_url(url, 3306)
  # Decode url-encoded information in the db connection string
  url['user'] = php.urldecode(url['user'])
  # Test if database url has a password.
  url['pass'] = (php.urldecode(url['pass']) if php.isset(url, 'pass') else '')
  url['host'] = php.urldecode(url['host'])
  url['path'] = php.urldecode(url['path'])
  if (not php.isset(url, 'port')):
    url['port'] = None
  connection  = DrupyMySQL.mysqli_real_connect(\
    url['host'], url['user'], url['pass'], php.substr(url['path'], 1), \
    url['port'], '', DrupyMySQL.MYSQLI_CLIENT_FOUND_ROWS)
  if (DrupyMySQL.mysqli_connect_errno() > 0):
    _db_error_page(DrupyMySQL.mysqli_connect_error())
  # Force UTF-8.
  DrupyMySQL.mysqli_query(connection, 'SET NAMES "utf8"')
  # Require ANSI mode to improve SQL portability.
  DrupyMySQL.mysqli_query(connection, "SET php.SESSION sql_mode='ANSI'")
  return connection
开发者ID:brendoncrawford,项目名称:drupy,代码行数:28,代码来源:database_mysqli.py

示例5: create_table_sql

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import substr [as 别名]
def create_table_sql(name, table):
  """
   Generate SQL to create a new table from a Drupal schema definition.
  
   @param name
     The name of the table to create.
   @param table
     A Schema API table definition array.
   @return
     An array of SQL statements to create the table.
  """
  if (php.empty(table['mysql_suffix'])):
    table['mysql_suffix'] = "/*not 40100 DEFAULT CHARACTER SET UTF8 */"
  sql = "CREATE TABLE {" +  name  + "} (\n"
  # Add the SQL statement for each field.
  for field_name,field in table['fields'].items():
    sql += _db_create_field_sql(field_name, _db_process_field(field)) +  ", \n"
  # Process keys & indexes.
  keys = _db_create_keys_sql(table)
  if (php.count(keys)):
    sql += php.implode(", \n", keys) +  ", \n"
  # Remove the last comma and space.
  sql = php.substr(sql, 0, -3) +  "\n) "
  sql += table['mysql_suffix']
  return array(sql)
开发者ID:brendoncrawford,项目名称:drupy,代码行数:27,代码来源:database_mysqli.py

示例6: directory_temp

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import substr [as 别名]
def directory_temp():
  """
   Determine the default temporary directory.
  
   @return A string containing a temp directory.
  """
  temporary_directory = variable_get('file_directory_temp', None)
  if (is_None(temporary_directory)):
    directories = []
    # Has PHP been set with an upload_tmp_dir?
    if (ini_get('upload_tmp_dir')):
      directories.append( ini_get('upload_tmp_dir') )
    # Operating system specific dirs.
    if (php.substr(PHP_OS, 0, 3) == 'WIN'):
      directories.append( 'c:\\windows\\temp' )
      directories.append( 'c:\\winnt\\temp' )
      path_delimiter = '\\'
    else:
      directories.append( '/tmp' )
      path_delimiter = '/'
    for directory in directories:
      if (not temporary_directory and php.is_dir(directory)):
        temporary_directory = directory
    # if a directory has been found, use it,
    # otherwise default to 'files/tmp' or 'files\\tmp'
    temporary_directory = (temporary_directory if \
      (temporary_directory != None) else \
      (file_directory_path() +  path_delimiter + 'tmp'))
    variable_set('file_directory_temp', temporary_directory)
  return temporary_directory
开发者ID:brendoncrawford,项目名称:drupy,代码行数:32,代码来源:file.py

示例7: scan_directory

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import substr [as 别名]
def scan_directory(dir, mask, nomask = ['.', '..', 'CVS'], \
    callback = 0, recurse = True, key = 'filename', min_depth = 0, depth = 0):
  """
   Finds all files that match a given mask in a given directory.
   Directories and files beginning with a period are excluded; this
   prevents hidden files and directories (such as SVN working directories)
   from being scanned.
  
   @param dir
     The base directory for the scan, without trailing slash.
   @param mask
     The regular expression of the files to find.
   @param nomask
     An array of files/directories to ignore.
   @param callback
     The callback function to call for each match.
   @param recurse
     When True, the directory scan will recurse the entire tree
     starting at the provided directory.
   @param key
     The key to be used for the returned array of files + Possible
     values are "filename", for the path starting with dir,
     "basename", for the basename of the file, and "name" for the name
     of the file without an extension.
   @param min_depth
     Minimum depth of directories to return files from.
   @param depth
     Current depth of recursion + This parameter is only used
     internally and should not be passed.
  
   @return
     An associative array (keyed on the provided key) of objects with
     "path", "basename", and "name" members corresponding to the
     matching files.
  """
  key = (key if php.in_array(key, \
    ('filename', 'basename', 'name')) else 'filename')
  files = []
  if php.is_dir(dir):
    dir_files = php.scandir(dir)
    for file in dir_files:
      if (not php.in_array(file, nomask) and file[0] != '.'):
        if (php.is_dir("%s/%s" % (dir, file)) and recurse):
          # Give priority to files in this folder by
          # merging them in after any subdirectory files.
          files = php.array_merge(file_scan_directory("%s/%s" % (dir, file), \
            mask, nomask, callback, recurse, key, min_depth, depth + 1), files)
        elif (depth >= min_depth and ereg(mask, file)):
          # Always use this match over anything already
          # set in files with the same $key.
          filename = "%s/%s" % (dir, file)
          basename_ = php.basename(file)
          name = php.substr(basename_, 0, php.strrpos(basename_, '.'))
          files[key] = php.stdClass()
          files[key].filename = filename
          files[key].basename = basename_
          files[key].name = name
          if (callback):
            callback(filename)
  return files
开发者ID:brendoncrawford,项目名称:drupy,代码行数:62,代码来源:file.py

示例8: set_active

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import substr [as 别名]
def set_active(name = 'default'):
  """
   Activate a database for future queries.
  
   If it is necessary to use external databases in a project, this function can
   be used to change where database queries are sent. If the database has not
   yet been used, it is initialized using the URL specified for that name in
   Drupal's configuration file. If this name is not defined, a duplicate of the
   default connection is made instead.
  
   Be sure to change the connection back to the default when done with custom
   code.
  
   @param name
     The name assigned to the newly active database connection. If omitted, the
     default connection will be made active.
  
   @return the name of the previously active database or FALSE if non was
   found.
  
   @todo BC: Need to eventually resolve the database importing mechanism here
   right now we are statically loading mysql at the top, but eventually we need
   to get this figured out 
  """
  php.static(set_active, 'db_conns', {})
  php.static(set_active, 'active_name', False)
  if (settings.db_url == None):
    install_goto('install.py');
  if (not php.isset(set_active.db_conns, name)):
    # Initiate a new connection, using the named DB URL specified.
    if (isinstance(settings.db_url, dict)):
      connect_url = (settings.db_url[name] if \
        php.array_key_exists(name, settings.db_url) else \
        settings.db_url['default']);
    else:
      connect_url = settings.db_url;
    lib_appglobals.db_type = \
      php.substr(connect_url, 0, php.strpos(connect_url, '://'));
    #handler = "includes/database_%(db_type)s.py" % {'db_type' : db_type};
    #try:
    #  import db file here
    #except ImportError:
    #  _db_error_page("The database type '" + db_type + \
    #    "' is unsupported. Please use either 'mysql' or " + \
    #    "'mysqli' for MySQL, or 'pgsql' for PostgreSQL databases.");
    set_active.db_conns[name] = db.connect(connect_url);
    # We need to pass around the simpletest database prefix in the request
    # and we put that in the user_agent php.header.
    if (php.preg_match("/^simpletest\d+$/", php.SERVER['HTTP_USER_AGENT'])):
      settings.db_prefix = php.SERVER['HTTP_USER_AGENT'];
  previous_name = set_active.active_name;
  # Set the active connection.
  set_active.active_name = name;
  lib_appglobals.active_db = set_active.db_conns[name];
  return previous_name;
开发者ID:brendoncrawford,项目名称:drupy,代码行数:57,代码来源:database.py

示例9: create_url

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import substr [as 别名]
def create_url(path):
  """
   Create the download path to a file.
  
   @param path A string containing the path of the file to generate URL for.
   @return A string containing a URL that can be used to download the file.
  """
  # Strip file_directory_path from path + We only include relative paths in urls.
  if (php.strpos(path, file_directory_path() + '/') == 0):
    path = php.trim(php.substr(path, php.strlen(file_directory_path())), '\\/')
  dls = variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC);
  if dls == FILE_DOWNLOADS_PUBLIC:
    return settings.base_url + '/' + file_directory_path() + '/' + \
      php.str_replace('\\', '/', path)
  elif dls == FILE_DOWNLOADS_PRIVATE:
    return url('system/files/' + path, {'absolute' : True})
开发者ID:brendoncrawford,项目名称:drupy,代码行数:18,代码来源:file.py

示例10: conf_init

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import substr [as 别名]
def conf_init():
    """
   Loads the configuration and sets the base URL, cookie domain, and
   session name correctly.
  """
    # These will come from settings
    # db_url, db_prefix, cookie_domain, conf, installed_profile, update_free_access
    if lib_appglobals.base_url != None:
        # Parse fixed base URL from settings.php.
        parts = php.parse_url(lib_appglobals.base_url)
        if not php.isset(parts, "path"):
            parts["path"] = ""
        lib_appglobals.base_path = parts["path"] + "/"
        # Build base_root (everything until first slash after "scheme://").
        lib_appglobals.base_root = php.substr(
            lib_appglobals.base_url, 0, php.strlen(lib_appglobals.base_url) - php.strlen(parts["path"])
        )
    else:
        # Create base URL
        lib_appglobals.base_root = (
            "https" if (php.isset(php.SERVER, "HTTPS") and php.SERVER["HTTPS"] == "on") else "http"
        )
        # As php.SERVER['HTTP_HOST'] is user input, ensure it only contains
        # characters allowed in hostnames.
        lib_appglobals.base_root += "://" + php.preg_replace("/[^a-z0-9-:._]/i", "", php.SERVER["HTTP_HOST"])
        lib_appglobals.base_url = lib_appglobals.base_root
        # php.SERVER['SCRIPT_NAME'] can, in contrast to php.SERVER['PHP_SELF'], not
        # be modified by a visitor.
        dir = php.trim(php.dirname(php.SERVER["SCRIPT_NAME"]), "\,/")
        if len(dir) > 0:
            lib_appglobals.base_path = "/dir"
            lib_appglobals.base_url += lib_appglobals.base_path
            lib_appglobals.base_path += "/"
        else:
            lib_appglobals.base_path = "/"
    if settings.cookie_domain != None:
        # If the user specifies the cookie domain, also use it for session name.
        session_name_ = settings.cookie_domain
    else:
        # Otherwise use base_url as session name, without the protocol
        # to use the same session identifiers across http and https.
        session_name_ = php.explode("://", lib_appglobals.base_url, 2)[1]
        # We escape the hostname because it can be modified by a visitor.
        if not php.empty(php.SERVER["HTTP_HOST"]):
            settings.cookie_domain = check_plain(php.SERVER["HTTP_HOST"])
    # To prevent session cookies from being hijacked, a user can configure the
    # SSL version of their website to only transfer session cookies via SSL by
    # using PHP's session.cookie_secure setting. The browser will then use two
    # separate session cookies for the HTTPS and HTTP versions of the site. So we
    # must use different session identifiers for HTTPS and HTTP to prevent a
    # cookie collision.
    if php.ini_get("session.cookie_secure"):
        session_name_ += "SSL"
    # Strip leading periods, www., and port numbers from cookie domain.
    settings.cookie_domain = php.ltrim(settings.cookie_domain, ".")
    if php.strpos(settings.cookie_domain, "www.") == 0:
        settings.cookie_domain = php.substr(settings.cookie_domain, 4)
    settings.cookie_domain = php.explode(":", settings.cookie_domain)
    settings.cookie_domain = "." + settings.cookie_domain[0]
    # Per RFC 2109, cookie domains must contain at least one dot other than the
    # first. For hosts such as 'localhost' or IP Addresses we don't set a
    # cookie domain.
    if php.count(php.explode(".", settings.cookie_domain)) > 2 and not php.is_numeric(
        php.str_replace(".", "", settings.cookie_domain)
    ):
        php.ini_set("session.cookie_domain", settings.cookie_domain)
    # print session_name;
    lib_session.name("SESS" + php.md5(session_name_))
开发者ID:sabren,项目名称:drupy,代码行数:70,代码来源:bootstrap.py

示例11: save_upload

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import substr [as 别名]
def save_upload(source, validators = {}, dest = False, \
    replace = FILE_EXISTS_RENAME):
  """
   Saves a file upload to a new location + The source file is validated as a
   proper upload and handled as such.
  
   The file will be added to the files table as a temporary file.
   Temporary files
   are periodically cleaned + To make the file permanent file call
   file_set_status() to change its status.
  
   @param source
     A string specifying the name of the upload field to save.
   @param validators
     An optional, associative array of callback functions used to validate the
     file + The keys are function names and the values arrays of callback
     parameters which will be passed in after the user and file objects + The
     functions should return an array of error messages, an empty array
     indicates that the file passed validation.
     The functions will be called in
     the order specified.
   @param dest
     A string containing the directory source should be copied to + If this is
     not provided or is not writable, the temporary directory will be used.
   @param replace
     A boolean indicating whether an existing file of the same name in the
     destination directory should overwritten + A False value will generate a
     new, unique filename in the destination directory.
   @return
     An object containing the file information, or False
     in the event of an error.
  """
  php.static(file_save_upload, 'upload_cache', {})
  # Add in our check of the the file name length.
  validators['file_validate_name_length'] = {}
  # Return cached objects without processing since the file will have
  # already been processed and the paths in FILES will be invalid.
  if (php.isset(file_save_upload.uploadcache, source)):
    return file_save_upload.uploadcache[source]
  # If a file was uploaded, process it.
  if (php.isset(p.FILES, 'files') and p.FILES['files']['name'][source] and \
      php.is_uploaded_file(p.FILES['files']['tmp_name'][source])):
    # Check for file upload errors and return False if a
    # lower level system error occurred.
    # @see http://php.net/manual/en/features.file-upload.errors.php
    if p.FILES['files']['error'][source] == UPLOAD_ERR_OK:
      pass
    elif p.FILES['files']['error'][source] == UPLOAD_ERR_INI_SIZE or \
        p.FILES['files']['error'][source] == UPLOAD_ERR_FORM_SIZE:
      drupal_set_message(t(\
        'The file %file could not be saved, because it exceeds %maxsize, ' + \
        'the maximum allowed size for uploads.', \
        {'%file' : source, '%maxsize' : \
        format_size(file_upload_max_size())}), 'error')
      return False
    elif p.FILES['files']['error'][source] == UPLOAD_ERR_PARTIAL or \
        p.FILES['files']['error'][source] == UPLOAD_ERR_NO_FILE:
      drupal_set_message(t('The file %file could not be saved, ' + \
        'because the upload did not complete.', {'%file' : source}), 'error')
      return False
    # Unknown error
    else:
      drupal_set_message(t('The file %file could not be saved. ' + \
        'An unknown error has occurred.', {'%file' : source}), 'error')
      return False
    # Build the list of non-munged extensions.
    # @todo: this should not be here + we need to figure out the right place.
    extensions = ''
    for rid,name in lib_appglobals.user.roles.items():
      extensions += ' ' + variable_get("upload_extensions_rid",
      variable_get('upload_extensions_default', \
        'jpg jpeg gif png txt html doc xls pdf ppt pps odt ods odp'))
    # Begin building file object.
    file = php.stdClass()
    file.filename = file_munge_filename(php.trim(\
      basename(p.FILES['files']['name'][source]), '.'), extensions)
    file.filepath = p.FILES['files']['tmp_name'][source]
    file.filemime = p.FILES['files']['type'][source]
    # Rename potentially executable files, to help prevent exploits.
    if (php.preg_match('/\.(php|pl|py|cgi|asp|js)$/i', file.filename) and \
        (php.substr(file.filename, -4) != '.txt')):
      file.filemime = 'text/plain'
      file.filepath += '.txt'
      file.filename += '.txt'
    # If the destination is not provided, or is not writable, then use the
    # temporary directory.
    if (php.empty(dest) or file_check_path(dest) == False):
      dest = file_directory_temp()
    file.source = source
    file.destination = file_destination(file_create_path(dest + '/' + \
      file.filename), replace)
    file.filesize = FILES['files']['size'][source]
    # Call the validation functions.
    errors = {}
    for function,args in validators.items():
      array_unshift(args, file)
      errors = php.array_merge(errors, function(*args))
    # Check for validation errors.
    if (not php.empty(errors)):
      message = t('The selected file %name could not be uploaded.', \
#.........这里部分代码省略.........
开发者ID:brendoncrawford,项目名称:drupy,代码行数:103,代码来源:file.py


注:本文中的lib.drupy.DrupyPHP.substr方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。