Search is not available for this dataset
text stringlengths 75 104k |
|---|
def combine_xml_points(l, units, handle_units):
"""Combine multiple Point tags into an array."""
ret = {}
for item in l:
for key, value in item.items():
ret.setdefault(key, []).append(value)
for key, value in ret.items():
if key != 'date':
ret[key] = handle_units... |
def parse_xml_dataset(elem, handle_units):
"""Create a netCDF-like dataset from XML data."""
points, units = zip(*[parse_xml_point(p) for p in elem.findall('point')])
# Group points by the contents of each point
datasets = {}
for p in points:
datasets.setdefault(tuple(p), []).append(p)
... |
def parse_csv_response(data, unit_handler):
"""Handle CSV-formatted HTTP responses."""
return squish([parse_csv_dataset(d, unit_handler) for d in data.split(b'\n\n')]) |
def parse_csv_header(line):
"""Parse the CSV header returned by TDS."""
units = {}
names = []
for var in line.split(','):
start = var.find('[')
if start < 0:
names.append(str(var))
continue
else:
names.append(str(var[:start]))
end = var... |
def parse_csv_dataset(data, handle_units):
"""Parse CSV data into a netCDF-like dataset."""
fobj = BytesIO(data)
names, units = parse_csv_header(fobj.readline().decode('utf-8'))
arrs = np.genfromtxt(fobj, dtype=None, names=names, delimiter=',', unpack=True,
converters={'date': l... |
def validate_query(self, query):
"""Validate a query.
Determines whether `query` is well-formed. This includes checking for all
required parameters, as well as checking parameters for valid values.
Parameters
----------
query : NCSSQuery
The query to validat... |
def get_data(self, query):
"""Fetch parsed data from a THREDDS server using NCSS.
Requests data from the NCSS endpoint given the parameters in `query` and
handles parsing of the returned content based on the mimetype.
Parameters
----------
query : NCSSQuery
... |
def projection_box(self, min_x, min_y, max_x, max_y):
"""Add a bounding box in projected (native) coordinates to the query.
This adds a request for a spatial bounding box, bounded by (`min_x`, `max_x`) for
x direction and (`min_y`, `max_y`) for the y direction. This modifies the query
i... |
def strides(self, time=None, spatial=None):
"""Set time and/or spatial (horizontal) strides.
This is only used on grid requests. Used to skip points in the returned data.
This modifies the query in-place, but returns `self` so that multiple queries
can be chained together on one line.
... |
def register(self, mimetype):
"""Register a function to handle a particular mimetype."""
def dec(func):
self._reg[mimetype] = func
return func
return dec |
def handle_typed_values(val, type_name, value_type):
"""Translate typed values into the appropriate python object.
Takes an element name, value, and type and returns a list
with the string value(s) properly converted to a python type.
TypedValues are handled in ucar.ma2.DataType in net... |
def _get_data(self, time, site_id):
r"""Download and parse upper air observations from an online archive.
Parameters
----------
time : datetime
The date and time of the desired observation.
site_id : str
The three letter ICAO identifier of the station fo... |
def _get_data_raw(self, time, site_id):
"""Download data from the University of Wyoming's upper air archive.
Parameters
----------
time : datetime
Date and time for which data should be downloaded
site_id : str
Site id for which data should be downloaded
... |
def read_ncstream_data(fobj):
"""Handle reading an NcStream v1 data block from a file-like object."""
data = read_proto_object(fobj, stream.Data)
if data.dataType in (stream.STRING, stream.OPAQUE) or data.vdata:
log.debug('Reading string/opaque/vlen')
num_obj = read_var_int(fobj)
log... |
def read_ncstream_err(fobj):
"""Handle reading an NcStream error from a file-like object and raise as error."""
err = read_proto_object(fobj, stream.Error)
raise RuntimeError(err.message) |
def read_messages(fobj, magic_table):
"""Read messages from a file-like object until stream is exhausted."""
messages = []
while True:
magic = read_magic(fobj)
if not magic:
break
func = magic_table.get(magic)
if func is not None:
messages.append(fun... |
def read_proto_object(fobj, klass):
"""Read a block of data and parse using the given protobuf object."""
log.debug('%s chunk', klass.__name__)
obj = klass()
obj.ParseFromString(read_block(fobj))
log.debug('Header: %s', str(obj))
return obj |
def read_block(fobj):
"""Read a block.
Reads a block from a file object by first reading the number of bytes to read, which must
be encoded as a variable-byte length integer.
Parameters
----------
fobj : file-like object
The file to read from.
Returns
-------
bytes
... |
def process_vlen(data_header, array):
"""Process vlen coming back from NCStream v2.
This takes the array of values and slices into an object array, with entries containing
the appropriate pieces of the original array. Sizes are controlled by the passed in
`data_header`.
Parameters
----------
... |
def datacol_to_array(datacol):
"""Convert DataCol from NCStream v2 into an array with appropriate type.
Depending on the data type specified, this extracts data from the appropriate members
and packs into a :class:`numpy.ndarray`, recursing as necessary for compound data types.
Parameters
--------... |
def reshape_array(data_header, array):
"""Extract the appropriate array shape from the header.
Can handle taking a data header and either bytes containing data or a StructureData
instance, which will have binary data as well as some additional information.
Parameters
----------
array : :class:... |
def data_type_to_numpy(datatype, unsigned=False):
"""Convert an ncstream datatype to a numpy one."""
basic_type = _dtypeLookup[datatype]
if datatype in (stream.STRING, stream.OPAQUE):
return np.dtype(basic_type)
if unsigned:
basic_type = basic_type.replace('i', 'u')
return np.dtype... |
def struct_to_dtype(struct):
"""Convert a Structure specification to a numpy structured dtype."""
# str() around name necessary because protobuf gives unicode names, but dtype doesn't
# support them on Python 2
fields = [(str(var.name), data_type_to_numpy(var.dataType, var.unsigned))
for v... |
def unpack_variable(var):
"""Unpack an NCStream Variable into information we can use."""
# If we actually get a structure instance, handle turning that into a variable
if var.dataType == stream.STRUCTURE:
return None, struct_to_dtype(var), 'Structure'
elif var.dataType == stream.SEQUENCE:
... |
def unpack_attribute(att):
"""Unpack an embedded attribute into a python or numpy object."""
if att.unsigned:
log.warning('Unsupported unsigned attribute!')
# TDS 5.0 now has a dataType attribute that takes precedence
if att.len == 0: # Empty
val = None
elif att.dataType == stream.... |
def read_var_int(file_obj):
"""Read a variable-length integer.
Parameters
----------
file_obj : file-like object
The file to read from.
Returns
-------
int
the variable-length value read
"""
# Read all bytes from here, stopping with the first one that does not have... |
def fetch_data(self, **var):
"""Retrieve data from CDMRemote for one or more variables."""
varstr = ','.join(name + self._convert_indices(ind)
for name, ind in var.items())
query = self.query().add_query_parameter(req='data', var=varstr)
return self._fetch(query... |
def query(self):
"""Generate a new query for CDMRemote.
This handles turning on compression if necessary.
Returns
-------
HTTPQuery
The created query.
"""
q = super(CDMRemote, self).query()
# Turn on compression if it's been set on the obje... |
def check_token(func):
"""检查 access token 是否有效."""
@wraps(func)
def wrapper(*args, **kwargs):
response = func(*args, **kwargs)
if response.status_code == 401:
raise InvalidToken('Access token invalid or no longer valid')
else:
return response
return wrappe... |
def upload(self, remote_path, file_content, ondup=None, **kwargs):
"""上传单个文件(<2G).
| 百度PCS服务目前支持最大2G的单个文件上传。
| 如需支持超大文件(>2G)的断点续传,请参考下面的“分片文件上传”方法。
:param remote_path: 网盘中文件的保存路径(包含文件名)。
必须以 /apps/ 开头。
.. warning::
... |
def upload_tmpfile(self, file_content, **kwargs):
"""分片上传—文件分片及上传.
百度 PCS 服务支持每次直接上传最大2G的单个文件。
如需支持上传超大文件(>2G),则可以通过组合调用分片文件上传的
``upload_tmpfile`` 方法和 ``upload_superfile`` 方法实现:
1. 首先,将超大文件分割为2G以内的单文件,并调用 ``upload_tmpfile``
将分片文件依次上传;
2. 其次,调用 ``upload_super... |
def upload_superfile(self, remote_path, block_list, ondup=None, **kwargs):
"""分片上传—合并分片文件.
与分片文件上传的 ``upload_tmpfile`` 方法配合使用,
可实现超大文件(>2G)上传,同时也可用于断点续传的场景。
:param remote_path: 网盘中文件的保存路径(包含文件名)。
必须以 /apps/ 开头。
.. warning::
... |
def mkdir(self, remote_path, **kwargs):
"""为当前用户创建一个目录.
:param remote_path: 网盘中目录的路径,必须以 /apps/ 开头。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
* 文件名或路径名开头结尾... |
def meta(self, remote_path, **kwargs):
"""获取单个文件或目录的元信息.
:param remote_path: 网盘中文件/目录的路径,必须以 /apps/ 开头。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
* 文件名或路径名... |
def list_files(self, remote_path, by=None, order=None,
limit=None, **kwargs):
"""获取目录下的文件列表.
:param remote_path: 网盘中目录的路径,必须以 /apps/ 开头。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " ... |
def move(self, from_path, to_path, **kwargs):
"""移动单个文件或目录.
:param from_path: 源文件/目录在网盘中的路径(包括文件名)。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
* 文件名或路径名开头结尾不能是 ``.`... |
def multi_move(self, path_list, **kwargs):
"""批量移动文件或目录.
:param path_list: 源文件地址和目标文件地址对列表:
>>> path_list = [
... ('/apps/test_sdk/test.txt', # 源文件
... '/apps/test_sdk/testmkdir/b.txt' # 目标文件
... |
def copy(self, from_path, to_path, **kwargs):
"""拷贝文件或目录.
:param from_path: 源文件/目录在网盘中的路径(包括文件名)。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
* 文件名或路径名开头结尾不能是 ``.``
... |
def delete(self, remote_path, **kwargs):
"""删除单个文件或目录.
.. warning::
* 文件/目录删除后默认临时存放在回收站内,删除文件或目录的临时存放
不占用用户的空间配额;
* 存放有效期为10天,10天内可还原回原路径下,10天后则永久删除。
:param remote_path: 网盘中文件/目录的路径,路径必须以 /apps/ 开头。
.. warning::
... |
def multi_delete(self, path_list, **kwargs):
"""批量删除文件或目录.
.. warning::
* 文件/目录删除后默认临时存放在回收站内,删除文件或目录的临时存放
不占用用户的空间配额;
* 存放有效期为10天,10天内可还原回原路径下,10天后则永久删除。
:param path_list: 网盘中文件/目录的路径列表,路径必须以 /apps/ 开头。
.. warning::
... |
def search(self, remote_path, keyword, recurrent='0', **kwargs):
"""按文件名搜索文件(不支持查找目录).
:param remote_path: 需要检索的目录路径,路径必须以 /apps/ 开头。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
... |
def thumbnail(self, remote_path, height, width, quality=100, **kwargs):
"""获取指定图片文件的缩略图.
:param remote_path: 源图片的路径,路径必须以 /apps/ 开头。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
... |
def diff(self, cursor='null', **kwargs):
"""文件增量更新操作查询接口.
本接口有数秒延迟,但保证返回结果为最终一致.
:param cursor: 用于标记更新断点。
* 首次调用cursor=null;
* 非首次调用,使用最后一次调用diff接口的返回结果
中的cursor。
:type cursor: str
:return: Response 对象
... |
def video_convert(self, remote_path, video_type, **kwargs):
"""对视频文件进行转码,实现实时观看视频功能.
可下载支持 HLS/M3U8 的 `媒体云播放器 SDK <HLSSDK_>`__ 配合使用.
.. _HLSSDK:
http://developer.baidu.com/wiki/index.php?title=docs/cplat/media/sdk
:param remote_path: 需要下载的视频文件路径,以/开头的绝对路径,
... |
def list_streams(self, file_type, start=0, limit=100,
filter_path=None, **kwargs):
"""以视频、音频、图片及文档四种类型的视图获取所创建应用程序下的
文件列表.
:param file_type: 类型分为video、audio、image及doc四种。
:param start: 返回条目控制起始值,缺省值为0。
:param limit: 返回条目控制长度,缺省为1000,可配置。
:param filter... |
def download_stream(self, remote_path, **kwargs):
"""为当前用户下载一个流式文件.其参数和返回结果与下载单个文件的相同.
:param remote_path: 需要下载的文件路径,以/开头的绝对路径,含文件名。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
... |
def rapid_upload(self, remote_path, content_length, content_md5,
content_crc32, slice_md5, ondup=None, **kwargs):
"""秒传一个文件.
.. warning::
* 被秒传文件必须大于256KB(即 256*1024 B)。
* 校验段为文件的前256KB,秒传接口需要提供校验段的MD5。
(非强一致接口,上传后请等待1秒后再读取)
:param remote... |
def add_download_task(self, source_url, remote_path,
rate_limit=None, timeout=60 * 60,
expires=None, callback='', **kwargs):
"""添加离线下载任务,实现单个文件离线下载.
:param source_url: 源文件的URL。
:param remote_path: 下载后的文件保存路径。
.. wa... |
def query_download_tasks(self, task_ids, operate_type=1,
expires=None, **kwargs):
"""根据任务ID号,查询离线下载任务信息及进度信息。
:param task_ids: 要查询的任务ID列表
:type task_ids: list or tuple
:param operate_type:
* 0:查任务信息
* 1... |
def list_download_tasks(self, need_task_info=1, start=0, limit=10, asc=0,
create_time=None, status=None, source_url=None,
remote_path=None, expires=None, **kwargs):
"""查询离线下载任务ID列表及任务信息.
:param need_task_info: 是否需要返回任务信息:
... |
def cancel_download_task(self, task_id, expires=None, **kwargs):
"""取消离线下载任务.
:param task_id: 要取消的任务ID号。
:type task_id: str
:param expires: 请求失效时间,如果有,则会校验。
:type expires: int
:return: Response 对象
"""
data = {
'expires': expires,
... |
def list_recycle_bin(self, start=0, limit=1000, **kwargs):
"""获取回收站中的文件及目录列表.
:param start: 返回条目的起始值,缺省值为0
:param limit: 返回条目的长度,缺省值为1000
:return: Response 对象
"""
params = {
'start': start,
'limit': limit,
}
return self._request('... |
def restore_recycle_bin(self, fs_id, **kwargs):
"""还原单个文件或目录(非强一致接口,调用后请sleep 1秒读取).
:param fs_id: 所还原的文件或目录在PCS的临时唯一标识ID。
:type fs_id: str
:return: Response 对象
"""
data = {
'fs_id': fs_id,
}
return self._request('file', 'restore', data=data,... |
def multi_restore_recycle_bin(self, fs_ids, **kwargs):
"""批量还原文件或目录(非强一致接口,调用后请sleep1秒 ).
:param fs_ids: 所还原的文件或目录在 PCS 的临时唯一标识 ID 的列表。
:type fs_ids: list or tuple
:return: Response 对象
"""
data = {
'param': json.dumps({
'list': [{'fs_id': fs_... |
def get_new_access_token(refresh_token, client_id, client_secret,
scope=None, **kwargs):
"""使用 Refresh Token 刷新以获得新的 Access Token.
:param refresh_token: 用于刷新 Access Token 用的 Refresh Token;
:param client_id: 应用的 API Key;
:param client_secret: 应用的 Secret Key;
:param scope: 以空... |
def login(self):
""" Login to verisure app api
Login before calling any read or write commands
"""
if os.path.exists(self._cookieFileName):
with open(self._cookieFileName, 'r') as cookieFile:
self._vid = cookieFile.read().strip()
try:
... |
def _get_installations(self):
""" Get information about installations """
response = None
for base_url in urls.BASE_URLS:
urls.BASE_URL = base_url
try:
response = requests.get(
urls.get_installations(self._username),
... |
def get_overview(self):
""" Get overview for installation """
response = None
try:
response = requests.get(
urls.overview(self._giid),
headers={
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept... |
def set_smartplug_state(self, device_label, state):
""" Turn on or off smartplug
Args:
device_label (str): Smartplug device label
state (boolean): new status, 'True' or 'False'
"""
response = None
try:
response = requests.post(
... |
def get_history(self, filters=(), pagesize=15, offset=0):
""" Get recent events
Args:
filters (string set): 'ARM', 'DISARM', 'FIRE', 'INTRUSION',
'TECHNICAL', 'SOS', 'WARNING', 'LOCK',
'UNLOCK'
pagesize (int): N... |
def get_climate(self, device_label):
""" Get climate history
Args:
device_label: device label of climate device
"""
response = None
try:
response = requests.get(
urls.climate(self._giid),
headers={
'Accep... |
def set_lock_state(self, code, device_label, state):
""" Lock or unlock
Args:
code (str): Lock code
device_label (str): device label of lock
state (str): 'lock' or 'unlock'
"""
response = None
try:
response = requests.put(
... |
def get_lock_state_transaction(self, transaction_id):
""" Get lock state transaction status
Args:
transaction_id: Transaction ID received from set_lock_state
"""
response = None
try:
response = requests.get(
urls.get_lockstate_transaction(... |
def get_lock_config(self, device_label):
""" Get lock configuration
Args:
device_label (str): device label of lock
"""
response = None
try:
response = requests.get(
urls.lockconfig(self._giid, device_label),
headers={
... |
def set_lock_config(self, device_label, volume=None, voice_level=None,
auto_lock_enabled=None):
""" Set lock configuration
Args:
device_label (str): device label of lock
volume (str): 'SILENCE', 'LOW' or 'HIGH'
voice_level (str): 'ESSENTIAL' o... |
def capture_image(self, device_label):
""" Capture smartcam image
Args:
device_label (str): device label of camera
"""
response = None
try:
response = requests.post(
urls.imagecapture(self._giid, device_label),
headers={
... |
def get_camera_imageseries(self, number_of_imageseries=10, offset=0):
""" Get smartcam image series
Args:
number_of_imageseries (int): number of image series to get
offset (int): skip offset amount of image series
"""
response = None
try:
resp... |
def download_image(self, device_label, image_id, file_name):
""" Download image taken by a smartcam
Args:
device_label (str): device label of camera
image_id (str): image id from image series
file_name (str): path to file
"""
response = None
t... |
def logout(self):
""" Logout and remove vid """
response = None
try:
response = requests.delete(
urls.login(),
headers={
'Cookie': 'vid={}'.format(self._vid)})
except requests.exceptions.RequestException as ex:
r... |
def set_heat_pump_mode(self, device_label, mode):
""" Set heatpump mode
Args:
mode (str): 'HEAT', 'COOL', 'FAN' or 'AUTO'
"""
response = None
try:
response = requests.put(
urls.set_heatpump_state(self._giid, device_label),
h... |
def set_heat_pump_feature(self, device_label, feature):
""" Set heatpump mode
Args:
feature: 'QUIET', 'ECONAVI', or 'POWERFUL'
"""
response = None
try:
response = requests.put(
urls.set_heatpump_feature(self._giid, device_label, feature),
... |
def print_result(overview, *names):
""" Print the result of a verisure request """
if names:
for name in names:
toprint = overview
for part in name.split('/'):
toprint = toprint[part]
print(json.dumps(toprint, indent=4, separators=(',', ': ')))
els... |
def main():
""" Start verisure command line """
parser = argparse.ArgumentParser(
description='Read or change status of verisure devices')
parser.add_argument(
'username',
help='MyPages username')
parser.add_argument(
'password',
help='MyPages password')
parse... |
def type_id(self):
"""
Shortcut to retrieving the ContentType id of the model.
"""
try:
return ContentType.objects.get_for_model(self.model, for_concrete_model=False).id
except DatabaseError as e:
raise DatabaseError("Unable to fetch ContentType object, is... |
def get_output_cache_key(self, placeholder_name, instance):
"""
.. versionadded:: 0.9
Return the default cache key which is used to store a rendered item.
By default, this function generates the cache key using :func:`get_output_cache_base_key`.
"""
cachekey = self.... |
def get_output_cache_keys(self, placeholder_name, instance):
"""
.. versionadded:: 0.9
Return the possible cache keys for a rendered item.
This method should be overwritten when implementing a function :func:`set_cached_output` method
or when implementing a :func:`get_o... |
def get_cached_output(self, placeholder_name, instance):
"""
.. versionadded:: 0.9
Return the cached output for a rendered item, or ``None`` if no output is cached.
This method can be overwritten to implement custom caching mechanisms.
By default, this function generate... |
def set_cached_output(self, placeholder_name, instance, output):
"""
.. versionadded:: 0.9
Store the cached output for a rendered item.
This method can be overwritten to implement custom caching mechanisms.
By default, this function generates the cache key using :func:`... |
def render(self, request, instance, **kwargs):
"""
The rendering/view function that displays a plugin model instance.
:param instance: An instance of the ``model`` the plugin uses.
:param request: The Django :class:`~django.http.HttpRequest` class containing the request parameters.
... |
def render_to_string(self, request, template, context, content_instance=None):
"""
Render a custom template with the :class:`~PluginContext` as context instance.
"""
if not content_instance:
content_instance = PluginContext(request)
content_instance.update(context)
... |
def register_frontend_media(request, media):
"""
Add a :class:`~django.forms.Media` class to the current request.
This will be rendered by the ``render_plugin_media`` template tag.
"""
if not hasattr(request, '_fluent_contents_frontend_media'):
request._fluent_contents_frontend_media = Media... |
def get_rendering_cache_key(placeholder_name, contentitem):
"""
Return a cache key for the content item output.
.. seealso::
The :func:`ContentItem.clear_cache() <fluent_contents.models.ContentItem.clear_cache>` function
can be used to remove the cache keys of a retrieved object.
"""
... |
def get_placeholder_cache_key(placeholder, language_code):
"""
Return a cache key for an existing placeholder object.
This key is used to cache the entire output of a placeholder.
"""
return _get_placeholder_cache_key_for_id(
placeholder.parent_type_id,
placeholder.parent_id,
... |
def get_placeholder_cache_key_for_parent(parent_object, placeholder_name, language_code):
"""
Return a cache key for a placeholder.
This key is used to cache the entire output of a placeholder.
"""
parent_type = ContentType.objects.get_for_model(parent_object)
return _get_placeholder_cache_key_... |
def remove_stale_items(self, stale_cts):
"""
See if there are items that point to a removed model.
"""
stale_ct_ids = list(stale_cts.keys())
items = (ContentItem.objects
.non_polymorphic() # very important, or polymorphic skips them on fetching derived data
... |
def remove_unreferenced_items(self, stale_cts):
"""
See if there are items that no longer point to an existing parent.
"""
stale_ct_ids = list(stale_cts.keys())
parent_types = (ContentItem.objects.order_by()
.exclude(polymorphic_ctype__in=stale_ct_ids)
... |
def __initial_minus_queryset(self):
"""
Gives all elements from self._initial having a slot value that is not already
in self.get_queryset()
"""
queryset = self.get_queryset()
def initial_not_in_queryset(initial):
for x in queryset:
if x.slot ... |
def _get_placeholder_arg(arg_name, placeholder):
"""
Validate and return the Placeholder object that the template variable points to.
"""
if placeholder is None:
raise RuntimeWarning(u"placeholder object is None")
elif isinstance(placeholder, Placeholder):
return placeholder
elif... |
def _split_js(media, domain):
"""
Extract the local or external URLs from a Media object.
"""
# Read internal property without creating new Media instance.
if not media._js:
return ImmutableMedia.empty_instance
needs_local = domain == 'local'
new_js = []
for url in media._js:
... |
def _split_css(media, domain):
"""
Extract the local or external URLs from a Media object.
"""
# Read internal property without creating new Media instance.
if not media._css:
return ImmutableMedia.empty_instance
needs_local = domain == 'local'
new_css = {}
for medium, url in si... |
def parse(cls, parser, token):
"""
Parse the node syntax:
.. code-block:: html+django
{% page_placeholder parentobj slotname title="test" role="m" %}
"""
bits, as_var = parse_as_var(parser, token)
tag_name, args, kwargs = parse_token_kwargs(parser, bits, all... |
def get_title(self):
"""
Return the string literal that is used in the template.
The title is used in the admin screens.
"""
try:
return extract_literal(self.meta_kwargs['title'])
except KeyError:
slot = self.get_slot()
if slot is not N... |
def extract_literal(templatevar):
"""
See if a template FilterExpression holds a literal value.
:type templatevar: django.template.FilterExpression
:rtype: bool|None
"""
# FilterExpression contains another 'var' that either contains a Variable or SafeData object.
if hasattr(templatevar, 'va... |
def extract_literal_bool(templatevar):
"""
See if a template FilterExpression holds a literal boolean value.
:type templatevar: django.template.FilterExpression
:rtype: bool|None
"""
# FilterExpression contains another 'var' that either contains a Variable or SafeData object.
if hasattr(tem... |
def _create_markup_plugin(language, model):
"""
Create a new MarkupPlugin class that represents the plugin type.
"""
form = type("{0}MarkupItemForm".format(language.capitalize()), (MarkupItemForm,), {
'default_language': language,
})
classname = "{0}MarkupPlugin".format(language.capital... |
def get_parent_lookup_kwargs(parent_object):
"""
Return lookup arguments for the generic ``parent_type`` / ``parent_id`` fields.
:param parent_object: The parent object.
:type parent_object: :class:`~django.db.models.Model`
"""
if parent_object is None:
return dict(
parent_t... |
def get_parent_active_language_choices(parent_object, exclude_current=False):
"""
.. versionadded:: 1.0
Get the currently active languages of an parent object.
Note: if there is no content at the page, the language won't be returned.
"""
assert parent_object is not None, "Missing parent_object... |
def get_by_slot(self, parent_object, slot):
"""
Return a placeholder by key.
"""
placeholder = self.parent(parent_object).get(slot=slot)
placeholder.parent = parent_object # fill the reverse cache
return placeholder |
def create_for_object(self, parent_object, slot, role='m', title=None):
"""
Create a placeholder with the given parameters
"""
from .db import Placeholder
parent_attrs = get_parent_lookup_kwargs(parent_object)
obj = self.create(
slot=slot,
role=rol... |
def translated(self, *language_codes):
"""
.. versionadded:: 1.0
Only return translated objects which of the given languages.
When no language codes are given, only the currently active language is returned.
"""
# this API has the same semantics as django-parler's .tran... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.