index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
37,328 | async_payok.asyncpayok | getPayments |
Получение всех транзакций\транзакции
:param offset: отсуп\пропуск указанного кол-ва строк
:type offset: Optional[int]
:return: данные об транзациях\транзакции
:rtype: Union[Transaction, List[Transaction]
| nit__(
d: int,
ey: str,
t_key: Optional[str],
id: Optional[int]
ne:
_API_URL__: str = "https://payok.io"
_API_ID__: int = api_id
_API_KEY__: str = api_key
_SECRET_KEY__: Optional[str] = secret_key
_SHOP_ID__: Optional[int] = shop_id
SSL_CONTEXT_ = ssl.create_default_context(cafile=certifi.where())
ession: ClientSession = ClientSession()
| (self, offset: Optional[int] = None) -> Union[async_payok.models.invoice.Invoice, List[async_payok.models.invoice.Invoice]] |
37,329 | async_payok.exceptions | PayOkAPIError | null | class PayOkAPIError(Exception):
pass
| null |
37,333 | commented_json | CommentedValue | null | class CommentedValue:
comment: str
value: JsonValue
| () |
37,334 | commented_json | dump | null | def dump(
obj: JsonValue,
fp,
*,
skipkeys=False,
ensure_ascii=True,
check_circular=True,
allow_nan=True,
indent=None,
separators=None,
default=None,
sort_keys=False,
**kw
):
return json.dump(
obj, fp,
skipkeys=skipkeys,
ensure_ascii=ensure_ascii,
check_circular=check_circular,
allow_nan=allow_nan,
indent=indent,
separators=separators,
default=default,
sort_keys=sort_keys,
**kw
)
| (obj: Union[str, int, float, bool, NoneType, List[Union[str, int, float, bool, NoneType, ForwardRef('JsonArray'), Dict[str, Union[str, int, float, bool, NoneType, ForwardRef('JsonArray'), ForwardRef('JsonObject'), commented_json.CommentedValue]], commented_json.CommentedValue]], Dict[str, Union[str, int, float, bool, NoneType, List[Union[str, int, float, bool, NoneType, ForwardRef('JsonArray'), ForwardRef('JsonObject'), commented_json.CommentedValue]], ForwardRef('JsonObject'), commented_json.CommentedValue]]], fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, default=None, sort_keys=False, **kw) |
37,335 | commented_json | dumps | null | def dumps(
obj: JsonValue,
*,
skipkeys=False,
ensure_ascii=True,
check_circular=True,
allow_nan=True,
indent=None,
separators=None,
default=None,
sort_keys=False,
**kw
) -> str:
return json.dumps(
obj,
skipkeys=skipkeys,
ensure_ascii=ensure_ascii,
check_circular=check_circular,
allow_nan=allow_nan,
indent=indent,
separators=separators,
default=default,
sort_keys=sort_keys,
**kw
)
| (obj: Union[str, int, float, bool, NoneType, List[Union[str, int, float, bool, NoneType, ForwardRef('JsonArray'), Dict[str, Union[str, int, float, bool, NoneType, ForwardRef('JsonArray'), ForwardRef('JsonObject'), commented_json.CommentedValue]], commented_json.CommentedValue]], Dict[str, Union[str, int, float, bool, NoneType, List[Union[str, int, float, bool, NoneType, ForwardRef('JsonArray'), ForwardRef('JsonObject'), commented_json.CommentedValue]], ForwardRef('JsonObject'), commented_json.CommentedValue]]], *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, default=None, sort_keys=False, **kw) -> str |
37,337 | exempledepackage | slt | null | def slt():
print("Ça marche")
return True
| () |
37,338 | weewx | CHECK_LOOP | Event issued in the main loop, right after a new LOOP packet has been
processed. Generally, it is used to throw an exception, breaking the main
loop, so the console can be used for other things. | class CHECK_LOOP(object):
"""Event issued in the main loop, right after a new LOOP packet has been
processed. Generally, it is used to throw an exception, breaking the main
loop, so the console can be used for other things."""
| () |
37,339 | weewx | CRCError | Exception thrown when unable to pass a CRC check. | class CRCError(WeeWxIOError):
"""Exception thrown when unable to pass a CRC check."""
| null |
37,340 | weewx | CannotCalculate | Exception raised when a type cannot be calculated. | class CannotCalculate(ValueError):
"""Exception raised when a type cannot be calculated."""
| null |
37,341 | weewx | END_ARCHIVE_PERIOD | Event issued at the end of an archive period. | class END_ARCHIVE_PERIOD(object):
"""Event issued at the end of an archive period."""
| () |
37,342 | weewx | Event | Represents an event. | class Event(object):
"""Represents an event."""
def __init__(self, event_type, **argv):
self.event_type = event_type
for key in argv:
setattr(self, key, argv[key])
def __str__(self):
"""Return a string with a reasonable representation of the event."""
et = "Event type: %s | " % self.event_type
s = "; ".join("%s: %s" % (k, self.__dict__[k]) for k in self.__dict__ if k != "event_type")
return et + s
| (event_type, **argv) |
37,343 | weewx | __init__ | null | def __init__(self, event_type, **argv):
self.event_type = event_type
for key in argv:
setattr(self, key, argv[key])
| (self, event_type, **argv) |
37,344 | weewx | __str__ | Return a string with a reasonable representation of the event. | def __str__(self):
"""Return a string with a reasonable representation of the event."""
et = "Event type: %s | " % self.event_type
s = "; ".join("%s: %s" % (k, self.__dict__[k]) for k in self.__dict__ if k != "event_type")
return et + s
| (self) |
37,345 | weewx | HardwareError | Exception thrown when an error is detected in the hardware. | class HardwareError(Exception):
"""Exception thrown when an error is detected in the hardware."""
| null |
37,346 | weewx | NEW_ARCHIVE_RECORD | Event issued when a new archive record is available. The event contains
attribute 'record', which is the new archive record. | class NEW_ARCHIVE_RECORD(object):
"""Event issued when a new archive record is available. The event contains
attribute 'record', which is the new archive record."""
| () |
37,347 | weewx | NEW_LOOP_PACKET | Event issued when a new LOOP packet is available. The event contains
attribute 'packet', which is the new LOOP packet. | class NEW_LOOP_PACKET(object):
"""Event issued when a new LOOP packet is available. The event contains
attribute 'packet', which is the new LOOP packet."""
| () |
37,348 | weewx | NoCalculate | Exception raised when a type does not need to be calculated. | class NoCalculate(Exception):
"""Exception raised when a type does not need to be calculated."""
| null |
37,349 | weewx | POST_LOOP | Event issued right after the main loop has been broken. Services hook
into this to access the console for things other than generating LOOP
packet. | class POST_LOOP(object):
"""Event issued right after the main loop has been broken. Services hook
into this to access the console for things other than generating LOOP
packet."""
| () |
37,350 | weewx | PRE_LOOP | Event issued just before the main packet loop is entered. Services
have been loaded. | class PRE_LOOP(object):
"""Event issued just before the main packet loop is entered. Services
have been loaded."""
| () |
37,351 | weewx | RetriesExceeded | Exception thrown when max retries exceeded. | class RetriesExceeded(WeeWxIOError):
"""Exception thrown when max retries exceeded."""
| null |
37,352 | weewx | STARTUP | Event issued when the engine first starts up. Services have been
loaded. | class STARTUP(object):
"""Event issued when the engine first starts up. Services have been
loaded."""
| () |
37,353 | weewx | StopNow | Exception thrown to stop the engine. | class StopNow(Exception):
"""Exception thrown to stop the engine."""
| null |
37,354 | weewx | UnitError | Exception thrown when there is a mismatch in unit systems. | class UnitError(ValueError):
"""Exception thrown when there is a mismatch in unit systems."""
| null |
37,355 | weewx | UnknownAggregation | Exception thrown for an unknown aggregation type | class UnknownAggregation(ValueError):
"""Exception thrown for an unknown aggregation type"""
| null |
37,356 | weewx | UnknownArchiveType | Exception thrown after reading an unrecognized archive type. | class UnknownArchiveType(HardwareError):
"""Exception thrown after reading an unrecognized archive type."""
| null |
37,357 | weewx | UnknownBinding | Exception thrown when attempting to use an unknown data binding. | class UnknownBinding(Exception):
"""Exception thrown when attempting to use an unknown data binding."""
| null |
37,358 | weewx | UnknownDatabase | Exception thrown when attempting to use an unknown database. | class UnknownDatabase(Exception):
"""Exception thrown when attempting to use an unknown database."""
| null |
37,359 | weewx | UnknownDatabaseType | Exception thrown when attempting to use an unknown database type. | class UnknownDatabaseType(Exception):
"""Exception thrown when attempting to use an unknown database type."""
| null |
37,360 | weewx | UnknownType | Exception thrown for an unknown observation type | class UnknownType(ValueError):
"""Exception thrown for an unknown observation type"""
| null |
37,361 | weewx | UnsupportedFeature | Exception thrown when attempting to access a feature that is not
supported (yet). | class UnsupportedFeature(Exception):
"""Exception thrown when attempting to access a feature that is not
supported (yet)."""
| null |
37,362 | weewx | ViolatedPrecondition | Exception thrown when a function is called with violated
preconditions. | class ViolatedPrecondition(Exception):
"""Exception thrown when a function is called with violated
preconditions."""
| null |
37,363 | weewx | WakeupError | Exception thrown when unable to wake up or initially connect with the
hardware. | class WakeupError(WeeWxIOError):
"""Exception thrown when unable to wake up or initially connect with the
hardware."""
| null |
37,364 | weewx | WeeWxIOError | Base class of exceptions thrown when encountering an input/output error
with the hardware. | class WeeWxIOError(IOError):
"""Base class of exceptions thrown when encountering an input/output error
with the hardware."""
| null |
37,365 | weewx | require_weewx_version | utility to check for version compatibility | def require_weewx_version(module, required_version):
"""utility to check for version compatibility"""
from weeutil.weeutil import version_compare
if version_compare(__version__, required_version) < 0:
raise UnsupportedFeature("%s requires weewx %s or greater, found %s"
% (module, required_version, __version__))
| (module, required_version) |
37,367 | semaphore_sms.client | SemaphoreClient | A client for accessing the Semaphore API. | class SemaphoreClient(object):
"""A client for accessing the Semaphore API."""
def __init__(
self,
api_key: Optional[str] = None,
sender_name: Optional[str] = None,
environment: Optional[MutableMapping[str, str]] = None,
):
"""
Initializes the Semapore SMS Client
:param api_key: Semaphore API key to authenticate with
:param sender_name: SMS sender name to use when sending messages (defaults to 'SEMAPHORE')
:param environment: Environment to look for auth details, defaults to os.environ
"""
environment = environment or os.environ
self.api_key = api_key or environment.get('SEMAPHORE_SMS_APIKEY')
self.sender_name = sender_name or environment.get('SEMAPHORE_SMS_SENDERNAME')
if not self.api_key:
raise SemaphoreException('Credentials are required to create a SemaphoreClient')
self.http_client = HttpClient()
self._account = None
def request(
self,
method: str,
uri: str,
params: Optional[Dict[str, object]] = None,
data: Optional[Dict[str, object]] = None,
timeout: float = 10,
allow_redirects: bool = False,
) -> dict:
"""
Makes a request to the Semaphore API.
:param method: HTTP Method
:param uri: Fully qualified url
:param params: Query string parameters
:param data: POST body data
:param timeout: Timeout in seconds, defaults to 10
:param allow_redirects: Should the client follow redirects
:returns: Response from the Semaphore API
"""
uri = f'{BASE_URI}{uri}/'
response = self.http_client.request(
method,
uri,
params=params,
data=data,
timeout=timeout,
allow_redirects=allow_redirects,
)
if response.ok:
# We assume that Semaphore API always returns JSON,
# and won't handle probable case of not receiving JSON type (YAGNI)
return response.json()
raise SemaphoreException(f'Request failed: HTTP {response.status_code} {response.text}')
def get(self, uri: str, params: Dict[str, object] = dict()) -> dict:
params = {
**params,
'apikey': self.api_key # automatically add apikey as query param
}
params = {k: v for k, v in params.items() if v is not None}
return self.request('get', uri, params, None)
def post(self, uri: str, data: Dict[str, object] = dict()) -> dict:
data = {
**data,
'apikey': self.api_key, # automatically add apikey in request data
'sendername': self.sender_name, # automatically add sender_name in request data
}
data = {k: v for k, v in data.items() if v is not None}
# make sure we re-fetch `account` next time it's called because a transaction has been triggered
self._account = None
return self.request('post', uri, None, data)
def validate_phone_format(self, number: Union[str, List[str]]):
"""
Philippine phone number validation, solely based on prefix and length
"""
clean_number = ''.join(number.split('-')).strip()
return re.match(r'^(\+?639|09)\d{9}$', clean_number)
def send(self, message: str, recipients: List[str], sender_name: Optional[str] = None):
"""
Used for hitting the send message endpoints (single and bulk).
https://semaphore.co/docs#sending_messages
https://semaphore.co/docs#bulk_messages
:param message: SMS body
:param recipients: Recipient PH phone number(s)
:param sender_name: SMS sender name (defaults to 'SEMAPHORE' if None)
:returns: Response from the Semaphore API
"""
sender_name = sender_name or self.sender_name
if not message.strip():
raise SemaphoreException('Cannot send a blank message')
if not all([self.validate_phone_format(recipient) for recipient in recipients]):
raise SemaphoreException('You supplied an invalid Philippine phone number in `recipients`')
return self.post(
'messages',
{
'message': message,
'sendername': sender_name,
'number': ','.join(recipients) # recipients are to be sent as a comma-separated string
}
)
def priority(self, message: str, recipients: List[str], sender_name: Optional[str] = None):
"""
Used for hitting the PRIORITY send message endpoint.
Similar to the normal send message endpoint, except that this takes more credits,
and will use the priority queue which bypasses the default message queue and
sends the message immediately.
https://semaphore.co/docs#priority_messages
:param message: SMS body
:param recipients: Recipient PH phone number(s)
:param sender_name: SMS sender name (defaults to 'SEMAPHORE' if None)
:returns: Response from the Semaphore API
"""
sender_name = sender_name or self.sender_name
if not message.strip():
raise SemaphoreException('Cannot send a blank message')
if not all([self.validate_phone_format(recipient) for recipient in recipients]):
raise SemaphoreException('You supplied an invalid Philippine phone number in `recipients`')
return self.post(
'priority',
{
'message': message,
'sendername': sender_name,
'number': ','.join(recipients) # recipients are to be sent as a comma-separated string
}
)
def otp(self, recipients: List[str], message: Optional[str] = None,
sender_name: Optional[str] = None, code: Optional[Union[int, str]] = None):
"""
Used for hitting the OTP message endpoint.
Similar to priority messaging, except this is dedicated for one-time password messages,
and uses a route dedicated to OTP traffic.
Please do not use this route to send regular messages.
https://semaphore.co/docs#otp_messages
:param message: Custom SMS body (please see docs for this)
:param recipients: Recipient PH phone number(s)
:param sender_name: SMS sender name (defaults to 'SEMAPHORE' if None)
:param code: Custom OTP code if you want to skip the auto-generated one
:returns: Response from the Semaphore API
"""
sender_name = sender_name or self.sender_name
if not all([self.validate_phone_format(recipient) for recipient in recipients]):
raise SemaphoreException('You supplied an invalid Philippine phone number in `recipients`')
return self.post(
'otp',
{
'message': message,
'sendername': sender_name,
'number': ','.join(recipients), # recipients are to be sent as a comma-separated string
'code': code,
}
)
def messages(self, id: Optional[Union[int, str]] = None, page: Optional[Union[int, str]] = None,
limit: Optional[Union[int, str]] = None, network: Optional[str] = None,
status: Optional[str] = None, start_date: Optional[str] = None, end_date: Optional[str] = None):
"""
Used for hitting the retrieve message(s) endpoint.
Providing `id` shall hit the /messages/<id>/ endpoint.
https://semaphore.co/docs#retrieving_messages
:param id: Specific message ID
:param page: Page of results to return.
:param limit: Only take top <limit> results. Default is 100, max is 1000.
:param network: which network the message was sent to
:param status: delivery status
:param start_date: YYYY-MM-DD
:param end_date: YYYY-MM-DD
:returns: Response from the Semaphore API
"""
uri = f'messages/{id}' if id else 'messages'
params = {
'page': page,
'limit': limit,
'startDate': start_date,
'endDate': end_date,
'network': network.lower() if network else None,
'status': status.lower() if status else None
}
return self.get(uri, params)
def transactions(self, page: Optional[Union[int, str]] = None, limit: Optional[Union[int, str]] = None):
"""
Retrieving transaction information under https://semaphore.co/docs#retrieving_account
:param page: Page of results to return.
:param limit: Only take top <limit> results. Default is 100, max is 1000.
:returns: Response from the Semaphore API
"""
params = {
'page': page,
'limit': limit
}
return self.get('account/transactions', params)
def sender_names(self, page: Optional[Union[int, str]] = None, limit: Optional[Union[int, str]] = None):
"""
Retrieving sender names under https://semaphore.co/docs#retrieving_account
:param page: Page of results to return.
:param limit: Only take top <limit> results. Default is 100, max is 1000.
:returns: Response from the Semaphore API
"""
params = {
'page': page,
'limit': limit
}
return self.get('account/sendernames', params)
def users(self, page: Optional[Union[int, str]] = None, limit: Optional[Union[int, str]] = None):
"""
Retrieving users under https://semaphore.co/docs#retrieving_account
:param page: Page of results to return.
:param limit: Only take top <limit> results. Default is 100, max is 1000.
:returns: Response from the Semaphore API
"""
params = {
'page': page,
'limit': limit
}
return self.get('account/users', params)
@property
def account(self):
"""
Used for retrieving basic information about your account
https://semaphore.co/docs#retrieving_account
"""
if not self._account:
self._account = self.get('account')
return self._account
| (api_key: Optional[str] = None, sender_name: Optional[str] = None, environment: Optional[MutableMapping[str, str]] = None) |
37,368 | semaphore_sms.client | __init__ |
Initializes the Semapore SMS Client
:param api_key: Semaphore API key to authenticate with
:param sender_name: SMS sender name to use when sending messages (defaults to 'SEMAPHORE')
:param environment: Environment to look for auth details, defaults to os.environ
| def __init__(
self,
api_key: Optional[str] = None,
sender_name: Optional[str] = None,
environment: Optional[MutableMapping[str, str]] = None,
):
"""
Initializes the Semapore SMS Client
:param api_key: Semaphore API key to authenticate with
:param sender_name: SMS sender name to use when sending messages (defaults to 'SEMAPHORE')
:param environment: Environment to look for auth details, defaults to os.environ
"""
environment = environment or os.environ
self.api_key = api_key or environment.get('SEMAPHORE_SMS_APIKEY')
self.sender_name = sender_name or environment.get('SEMAPHORE_SMS_SENDERNAME')
if not self.api_key:
raise SemaphoreException('Credentials are required to create a SemaphoreClient')
self.http_client = HttpClient()
self._account = None
| (self, api_key: Optional[str] = None, sender_name: Optional[str] = None, environment: Optional[MutableMapping[str, str]] = None) |
37,369 | semaphore_sms.client | get | null | def get(self, uri: str, params: Dict[str, object] = dict()) -> dict:
params = {
**params,
'apikey': self.api_key # automatically add apikey as query param
}
params = {k: v for k, v in params.items() if v is not None}
return self.request('get', uri, params, None)
| (self, uri: str, params: Dict[str, object] = {}) -> dict |
37,370 | semaphore_sms.client | messages |
Used for hitting the retrieve message(s) endpoint.
Providing `id` shall hit the /messages/<id>/ endpoint.
https://semaphore.co/docs#retrieving_messages
:param id: Specific message ID
:param page: Page of results to return.
:param limit: Only take top <limit> results. Default is 100, max is 1000.
:param network: which network the message was sent to
:param status: delivery status
:param start_date: YYYY-MM-DD
:param end_date: YYYY-MM-DD
:returns: Response from the Semaphore API
| def messages(self, id: Optional[Union[int, str]] = None, page: Optional[Union[int, str]] = None,
limit: Optional[Union[int, str]] = None, network: Optional[str] = None,
status: Optional[str] = None, start_date: Optional[str] = None, end_date: Optional[str] = None):
"""
Used for hitting the retrieve message(s) endpoint.
Providing `id` shall hit the /messages/<id>/ endpoint.
https://semaphore.co/docs#retrieving_messages
:param id: Specific message ID
:param page: Page of results to return.
:param limit: Only take top <limit> results. Default is 100, max is 1000.
:param network: which network the message was sent to
:param status: delivery status
:param start_date: YYYY-MM-DD
:param end_date: YYYY-MM-DD
:returns: Response from the Semaphore API
"""
uri = f'messages/{id}' if id else 'messages'
params = {
'page': page,
'limit': limit,
'startDate': start_date,
'endDate': end_date,
'network': network.lower() if network else None,
'status': status.lower() if status else None
}
return self.get(uri, params)
| (self, id: Union[int, str, NoneType] = None, page: Union[int, str, NoneType] = None, limit: Union[int, str, NoneType] = None, network: Optional[str] = None, status: Optional[str] = None, start_date: Optional[str] = None, end_date: Optional[str] = None) |
37,371 | semaphore_sms.client | otp |
Used for hitting the OTP message endpoint.
Similar to priority messaging, except this is dedicated for one-time password messages,
and uses a route dedicated to OTP traffic.
Please do not use this route to send regular messages.
https://semaphore.co/docs#otp_messages
:param message: Custom SMS body (please see docs for this)
:param recipients: Recipient PH phone number(s)
:param sender_name: SMS sender name (defaults to 'SEMAPHORE' if None)
:param code: Custom OTP code if you want to skip the auto-generated one
:returns: Response from the Semaphore API
| def otp(self, recipients: List[str], message: Optional[str] = None,
sender_name: Optional[str] = None, code: Optional[Union[int, str]] = None):
"""
Used for hitting the OTP message endpoint.
Similar to priority messaging, except this is dedicated for one-time password messages,
and uses a route dedicated to OTP traffic.
Please do not use this route to send regular messages.
https://semaphore.co/docs#otp_messages
:param message: Custom SMS body (please see docs for this)
:param recipients: Recipient PH phone number(s)
:param sender_name: SMS sender name (defaults to 'SEMAPHORE' if None)
:param code: Custom OTP code if you want to skip the auto-generated one
:returns: Response from the Semaphore API
"""
sender_name = sender_name or self.sender_name
if not all([self.validate_phone_format(recipient) for recipient in recipients]):
raise SemaphoreException('You supplied an invalid Philippine phone number in `recipients`')
return self.post(
'otp',
{
'message': message,
'sendername': sender_name,
'number': ','.join(recipients), # recipients are to be sent as a comma-separated string
'code': code,
}
)
| (self, recipients: List[str], message: Optional[str] = None, sender_name: Optional[str] = None, code: Union[int, str, NoneType] = None) |
37,372 | semaphore_sms.client | post | null | def post(self, uri: str, data: Dict[str, object] = dict()) -> dict:
data = {
**data,
'apikey': self.api_key, # automatically add apikey in request data
'sendername': self.sender_name, # automatically add sender_name in request data
}
data = {k: v for k, v in data.items() if v is not None}
# make sure we re-fetch `account` next time it's called because a transaction has been triggered
self._account = None
return self.request('post', uri, None, data)
| (self, uri: str, data: Dict[str, object] = {}) -> dict |
37,373 | semaphore_sms.client | priority |
Used for hitting the PRIORITY send message endpoint.
Similar to the normal send message endpoint, except that this takes more credits,
and will use the priority queue which bypasses the default message queue and
sends the message immediately.
https://semaphore.co/docs#priority_messages
:param message: SMS body
:param recipients: Recipient PH phone number(s)
:param sender_name: SMS sender name (defaults to 'SEMAPHORE' if None)
:returns: Response from the Semaphore API
| def priority(self, message: str, recipients: List[str], sender_name: Optional[str] = None):
"""
Used for hitting the PRIORITY send message endpoint.
Similar to the normal send message endpoint, except that this takes more credits,
and will use the priority queue which bypasses the default message queue and
sends the message immediately.
https://semaphore.co/docs#priority_messages
:param message: SMS body
:param recipients: Recipient PH phone number(s)
:param sender_name: SMS sender name (defaults to 'SEMAPHORE' if None)
:returns: Response from the Semaphore API
"""
sender_name = sender_name or self.sender_name
if not message.strip():
raise SemaphoreException('Cannot send a blank message')
if not all([self.validate_phone_format(recipient) for recipient in recipients]):
raise SemaphoreException('You supplied an invalid Philippine phone number in `recipients`')
return self.post(
'priority',
{
'message': message,
'sendername': sender_name,
'number': ','.join(recipients) # recipients are to be sent as a comma-separated string
}
)
| (self, message: str, recipients: List[str], sender_name: Optional[str] = None) |
37,374 | semaphore_sms.client | request |
Makes a request to the Semaphore API.
:param method: HTTP Method
:param uri: Fully qualified url
:param params: Query string parameters
:param data: POST body data
:param timeout: Timeout in seconds, defaults to 10
:param allow_redirects: Should the client follow redirects
:returns: Response from the Semaphore API
| def request(
self,
method: str,
uri: str,
params: Optional[Dict[str, object]] = None,
data: Optional[Dict[str, object]] = None,
timeout: float = 10,
allow_redirects: bool = False,
) -> dict:
"""
Makes a request to the Semaphore API.
:param method: HTTP Method
:param uri: Fully qualified url
:param params: Query string parameters
:param data: POST body data
:param timeout: Timeout in seconds, defaults to 10
:param allow_redirects: Should the client follow redirects
:returns: Response from the Semaphore API
"""
uri = f'{BASE_URI}{uri}/'
response = self.http_client.request(
method,
uri,
params=params,
data=data,
timeout=timeout,
allow_redirects=allow_redirects,
)
if response.ok:
# We assume that Semaphore API always returns JSON,
# and won't handle probable case of not receiving JSON type (YAGNI)
return response.json()
raise SemaphoreException(f'Request failed: HTTP {response.status_code} {response.text}')
| (self, method: str, uri: str, params: Optional[Dict[str, object]] = None, data: Optional[Dict[str, object]] = None, timeout: float = 10, allow_redirects: bool = False) -> dict |
37,375 | semaphore_sms.client | send |
Used for hitting the send message endpoints (single and bulk).
https://semaphore.co/docs#sending_messages
https://semaphore.co/docs#bulk_messages
:param message: SMS body
:param recipients: Recipient PH phone number(s)
:param sender_name: SMS sender name (defaults to 'SEMAPHORE' if None)
:returns: Response from the Semaphore API
| def send(self, message: str, recipients: List[str], sender_name: Optional[str] = None):
"""
Used for hitting the send message endpoints (single and bulk).
https://semaphore.co/docs#sending_messages
https://semaphore.co/docs#bulk_messages
:param message: SMS body
:param recipients: Recipient PH phone number(s)
:param sender_name: SMS sender name (defaults to 'SEMAPHORE' if None)
:returns: Response from the Semaphore API
"""
sender_name = sender_name or self.sender_name
if not message.strip():
raise SemaphoreException('Cannot send a blank message')
if not all([self.validate_phone_format(recipient) for recipient in recipients]):
raise SemaphoreException('You supplied an invalid Philippine phone number in `recipients`')
return self.post(
'messages',
{
'message': message,
'sendername': sender_name,
'number': ','.join(recipients) # recipients are to be sent as a comma-separated string
}
)
| (self, message: str, recipients: List[str], sender_name: Optional[str] = None) |
37,376 | semaphore_sms.client | sender_names |
Retrieving sender names under https://semaphore.co/docs#retrieving_account
:param page: Page of results to return.
:param limit: Only take top <limit> results. Default is 100, max is 1000.
:returns: Response from the Semaphore API
| def sender_names(self, page: Optional[Union[int, str]] = None, limit: Optional[Union[int, str]] = None):
"""
Retrieving sender names under https://semaphore.co/docs#retrieving_account
:param page: Page of results to return.
:param limit: Only take top <limit> results. Default is 100, max is 1000.
:returns: Response from the Semaphore API
"""
params = {
'page': page,
'limit': limit
}
return self.get('account/sendernames', params)
| (self, page: Union[int, str, NoneType] = None, limit: Union[int, str, NoneType] = None) |
37,377 | semaphore_sms.client | transactions |
Retrieving transaction information under https://semaphore.co/docs#retrieving_account
:param page: Page of results to return.
:param limit: Only take top <limit> results. Default is 100, max is 1000.
:returns: Response from the Semaphore API
| def transactions(self, page: Optional[Union[int, str]] = None, limit: Optional[Union[int, str]] = None):
"""
Retrieving transaction information under https://semaphore.co/docs#retrieving_account
:param page: Page of results to return.
:param limit: Only take top <limit> results. Default is 100, max is 1000.
:returns: Response from the Semaphore API
"""
params = {
'page': page,
'limit': limit
}
return self.get('account/transactions', params)
| (self, page: Union[int, str, NoneType] = None, limit: Union[int, str, NoneType] = None) |
37,378 | semaphore_sms.client | users |
Retrieving users under https://semaphore.co/docs#retrieving_account
:param page: Page of results to return.
:param limit: Only take top <limit> results. Default is 100, max is 1000.
:returns: Response from the Semaphore API
| def users(self, page: Optional[Union[int, str]] = None, limit: Optional[Union[int, str]] = None):
"""
Retrieving users under https://semaphore.co/docs#retrieving_account
:param page: Page of results to return.
:param limit: Only take top <limit> results. Default is 100, max is 1000.
:returns: Response from the Semaphore API
"""
params = {
'page': page,
'limit': limit
}
return self.get('account/users', params)
| (self, page: Union[int, str, NoneType] = None, limit: Union[int, str, NoneType] = None) |
37,379 | semaphore_sms.client | validate_phone_format |
Philippine phone number validation, solely based on prefix and length
| def validate_phone_format(self, number: Union[str, List[str]]):
"""
Philippine phone number validation, solely based on prefix and length
"""
clean_number = ''.join(number.split('-')).strip()
return re.match(r'^(\+?639|09)\d{9}$', clean_number)
| (self, number: Union[str, List[str]]) |
37,427 | flask_debugtoolbar.toolbar | DebugToolbar | null | class DebugToolbar(object):
_cached_panel_classes = {}
def __init__(self, request, jinja_env):
self.jinja_env = jinja_env
self.request = request
self.panels = []
self.template_context = {
'static_path': url_for('_debug_toolbar.static', filename='')
}
self.create_panels()
def create_panels(self):
"""
Populate debug panels
"""
activated = self.request.cookies.get('fldt_active', '')
activated = unquote(activated).split(';')
for panel_class in self._iter_panels(current_app):
panel_instance = panel_class(jinja_env=self.jinja_env,
context=self.template_context)
if panel_instance.dom_id() in activated:
panel_instance.is_active = True
self.panels.append(panel_instance)
def render_toolbar(self):
context = self.template_context.copy()
context.update({'panels': self.panels})
template = self.jinja_env.get_template('base.html')
return template.render(**context)
@classmethod
def load_panels(cls, app):
for panel_class in cls._iter_panels(app):
# Call `.init_app()` on panels
panel_class.init_app(app)
@classmethod
def _iter_panels(cls, app):
for panel_path in app.config['DEBUG_TB_PANELS']:
panel_class = cls._import_panel(app, panel_path)
if panel_class is not None:
yield panel_class
@classmethod
def _import_panel(cls, app, path):
cache = cls._cached_panel_classes
try:
return cache[path]
except KeyError:
pass
try:
panel_class = import_string(path)
except ImportError as e:
app.logger.warning('Disabled %s due to ImportError: %s', path, e)
panel_class = None
cache[path] = panel_class
return panel_class
| (request, jinja_env) |
37,428 | flask_debugtoolbar.toolbar | __init__ | null | def __init__(self, request, jinja_env):
self.jinja_env = jinja_env
self.request = request
self.panels = []
self.template_context = {
'static_path': url_for('_debug_toolbar.static', filename='')
}
self.create_panels()
| (self, request, jinja_env) |
37,429 | flask_debugtoolbar.toolbar | create_panels |
Populate debug panels
| def create_panels(self):
"""
Populate debug panels
"""
activated = self.request.cookies.get('fldt_active', '')
activated = unquote(activated).split(';')
for panel_class in self._iter_panels(current_app):
panel_instance = panel_class(jinja_env=self.jinja_env,
context=self.template_context)
if panel_instance.dom_id() in activated:
panel_instance.is_active = True
self.panels.append(panel_instance)
| (self) |
37,430 | flask_debugtoolbar.toolbar | render_toolbar | null | def render_toolbar(self):
context = self.template_context.copy()
context.update({'panels': self.panels})
template = self.jinja_env.get_template('base.html')
return template.render(**context)
| (self) |
37,431 | flask_debugtoolbar | DebugToolbarExtension | null | class DebugToolbarExtension(object):
_static_dir = os.path.realpath(
os.path.join(os.path.dirname(__file__), 'static'))
_toolbar_codes = [200, 201, 400, 401, 403, 404, 405, 500, 501, 502, 503, 504]
_redirect_codes = [301, 302, 303, 304]
def __init__(self, app=None):
self.app = app
# Support threads running `flask.copy_current_request_context` without
# poping toolbar during `teardown_request`
self.debug_toolbars_var = contextvars.ContextVar('debug_toolbars')
jinja_extensions = ['jinja2.ext.i18n']
if __jinja_version__[0] == '2':
jinja_extensions.append('jinja2.ext.with_')
# Configure jinja for the internal templates and add url rules
# for static data
self.jinja_env = Environment(
autoescape=True,
extensions=jinja_extensions,
loader=PackageLoader(__name__, 'templates'))
self.jinja_env.filters['urlencode'] = urllib.parse.quote_plus
self.jinja_env.filters['printable'] = _printable
self.jinja_env.globals['url_for'] = url_for
if app is not None:
self.init_app(app)
def init_app(self, app):
for k, v in iteritems(self._default_config(app)):
app.config.setdefault(k, v)
if not app.config['DEBUG_TB_ENABLED']:
return
if not app.config.get('SECRET_KEY'):
raise RuntimeError(
"The Flask-DebugToolbar requires the 'SECRET_KEY' config "
"var to be set")
DebugToolbar.load_panels(app)
app.before_request(self.process_request)
app.after_request(self.process_response)
app.teardown_request(self.teardown_request)
# Monkey-patch the Flask.dispatch_request method
app.dispatch_request = self.dispatch_request
app.add_url_rule('/_debug_toolbar/static/<path:filename>',
'_debug_toolbar.static', self.send_static_file)
app.register_blueprint(module, url_prefix='/_debug_toolbar/views')
def _default_config(self, app):
return {
'DEBUG_TB_ENABLED': app.debug,
'DEBUG_TB_HOSTS': (),
'DEBUG_TB_INTERCEPT_REDIRECTS': True,
'DEBUG_TB_PANELS': (
'flask_debugtoolbar.panels.versions.VersionDebugPanel',
'flask_debugtoolbar.panels.timer.TimerDebugPanel',
'flask_debugtoolbar.panels.headers.HeaderDebugPanel',
'flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel',
'flask_debugtoolbar.panels.config_vars.ConfigVarsDebugPanel',
'flask_debugtoolbar.panels.template.TemplateDebugPanel',
'flask_debugtoolbar.panels.sqlalchemy.SQLAlchemyDebugPanel',
'flask_debugtoolbar.panels.logger.LoggingPanel',
'flask_debugtoolbar.panels.route_list.RouteListDebugPanel',
'flask_debugtoolbar.panels.profiler.ProfilerDebugPanel',
'flask_debugtoolbar.panels.g.GDebugPanel',
),
'SQLALCHEMY_RECORD_QUERIES': app.debug,
}
def dispatch_request(self):
"""Modified version of Flask.dispatch_request to call process_view."""
req = request_ctx.request
app = current_app
if req.routing_exception is not None:
app.raise_routing_exception(req)
rule = req.url_rule
# if we provide automatic options for this URL and the
# request came with the OPTIONS method, reply automatically
if getattr(rule, 'provide_automatic_options', False) \
and req.method == 'OPTIONS':
return app.make_default_options_response()
# otherwise dispatch to the handler for that endpoint
view_func = app.view_functions[rule.endpoint]
view_func = self.process_view(app, view_func, req.view_args)
return view_func(**req.view_args)
def _show_toolbar(self):
"""Return a boolean to indicate if we need to show the toolbar."""
if request.blueprint == 'debugtoolbar':
return False
hosts = current_app.config['DEBUG_TB_HOSTS']
if hosts and request.remote_addr not in hosts:
return False
return True
def send_static_file(self, filename):
"""Send a static file from the flask-debugtoolbar static directory."""
return send_from_directory(self._static_dir, filename)
def process_request(self):
g.debug_toolbar = self
if not self._show_toolbar():
return
real_request = request._get_current_object()
self.debug_toolbars_var.set({})
self.debug_toolbars_var.get()[real_request] = (
DebugToolbar(real_request, self.jinja_env))
for panel in self.debug_toolbars_var.get()[real_request].panels:
panel.process_request(real_request)
def process_view(self, app, view_func, view_kwargs):
""" This method is called just before the flask view is called.
This is done by the dispatch_request method.
"""
real_request = request._get_current_object()
try:
toolbar = self.debug_toolbars_var.get({})[real_request]
except KeyError:
return view_func
for panel in toolbar.panels:
new_view = panel.process_view(real_request, view_func, view_kwargs)
if new_view:
view_func = new_view
return view_func
def process_response(self, response):
real_request = request._get_current_object()
if real_request not in self.debug_toolbars_var.get({}):
return response
# Intercept http redirect codes and display an html page with a
# link to the target.
if current_app.config['DEBUG_TB_INTERCEPT_REDIRECTS']:
if response.status_code in self._redirect_codes:
redirect_to = response.location
redirect_code = response.status_code
if redirect_to:
content = self.render('redirect.html', {
'redirect_to': redirect_to,
'redirect_code': redirect_code
})
response.content_length = len(content)
response.location = None
response.response = [content]
response.status_code = 200
# If the http response code is an allowed code then we process to add the
# toolbar to the returned html response.
if not (response.status_code in self._toolbar_codes and
response.is_sequence and
response.headers['content-type'].startswith('text/html')):
return response
content_encoding = response.headers.get('Content-Encoding')
if content_encoding and 'gzip' in content_encoding:
response_html = gzip_decompress(response.data).decode()
else:
response_html = response.get_data(as_text=True)
no_case = response_html.lower()
body_end = no_case.rfind('</body>')
if body_end >= 0:
before = response_html[:body_end]
after = response_html[body_end:]
elif no_case.startswith('<!doctype html>'):
before = response_html
after = ''
else:
warnings.warn('Could not insert debug toolbar.'
' </body> tag not found in response.')
return response
toolbar = self.debug_toolbars_var.get()[real_request]
for panel in toolbar.panels:
panel.process_response(real_request, response)
toolbar_html = toolbar.render_toolbar()
content = ''.join((before, toolbar_html, after))
content = content.encode('utf-8')
if content_encoding and 'gzip' in content_encoding:
content = gzip_compress(content)
response.response = [content]
response.content_length = len(content)
return response
def teardown_request(self, exc):
# debug_toolbars_var won't be set under `flask.copy_current_request_context`
self.debug_toolbars_var.get({}).pop(request._get_current_object(), None)
def render(self, template_name, context):
template = self.jinja_env.get_template(template_name)
return template.render(**context)
| (app=None) |
37,432 | flask_debugtoolbar | __init__ | null | def __init__(self, app=None):
self.app = app
# Support threads running `flask.copy_current_request_context` without
# poping toolbar during `teardown_request`
self.debug_toolbars_var = contextvars.ContextVar('debug_toolbars')
jinja_extensions = ['jinja2.ext.i18n']
if __jinja_version__[0] == '2':
jinja_extensions.append('jinja2.ext.with_')
# Configure jinja for the internal templates and add url rules
# for static data
self.jinja_env = Environment(
autoescape=True,
extensions=jinja_extensions,
loader=PackageLoader(__name__, 'templates'))
self.jinja_env.filters['urlencode'] = urllib.parse.quote_plus
self.jinja_env.filters['printable'] = _printable
self.jinja_env.globals['url_for'] = url_for
if app is not None:
self.init_app(app)
| (self, app=None) |
37,433 | flask_debugtoolbar | _default_config | null | def _default_config(self, app):
return {
'DEBUG_TB_ENABLED': app.debug,
'DEBUG_TB_HOSTS': (),
'DEBUG_TB_INTERCEPT_REDIRECTS': True,
'DEBUG_TB_PANELS': (
'flask_debugtoolbar.panels.versions.VersionDebugPanel',
'flask_debugtoolbar.panels.timer.TimerDebugPanel',
'flask_debugtoolbar.panels.headers.HeaderDebugPanel',
'flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel',
'flask_debugtoolbar.panels.config_vars.ConfigVarsDebugPanel',
'flask_debugtoolbar.panels.template.TemplateDebugPanel',
'flask_debugtoolbar.panels.sqlalchemy.SQLAlchemyDebugPanel',
'flask_debugtoolbar.panels.logger.LoggingPanel',
'flask_debugtoolbar.panels.route_list.RouteListDebugPanel',
'flask_debugtoolbar.panels.profiler.ProfilerDebugPanel',
'flask_debugtoolbar.panels.g.GDebugPanel',
),
'SQLALCHEMY_RECORD_QUERIES': app.debug,
}
| (self, app) |
37,434 | flask_debugtoolbar | _show_toolbar | Return a boolean to indicate if we need to show the toolbar. | def _show_toolbar(self):
"""Return a boolean to indicate if we need to show the toolbar."""
if request.blueprint == 'debugtoolbar':
return False
hosts = current_app.config['DEBUG_TB_HOSTS']
if hosts and request.remote_addr not in hosts:
return False
return True
| (self) |
37,435 | flask_debugtoolbar | dispatch_request | Modified version of Flask.dispatch_request to call process_view. | def dispatch_request(self):
"""Modified version of Flask.dispatch_request to call process_view."""
req = request_ctx.request
app = current_app
if req.routing_exception is not None:
app.raise_routing_exception(req)
rule = req.url_rule
# if we provide automatic options for this URL and the
# request came with the OPTIONS method, reply automatically
if getattr(rule, 'provide_automatic_options', False) \
and req.method == 'OPTIONS':
return app.make_default_options_response()
# otherwise dispatch to the handler for that endpoint
view_func = app.view_functions[rule.endpoint]
view_func = self.process_view(app, view_func, req.view_args)
return view_func(**req.view_args)
| (self) |
37,436 | flask_debugtoolbar | init_app | null | def init_app(self, app):
for k, v in iteritems(self._default_config(app)):
app.config.setdefault(k, v)
if not app.config['DEBUG_TB_ENABLED']:
return
if not app.config.get('SECRET_KEY'):
raise RuntimeError(
"The Flask-DebugToolbar requires the 'SECRET_KEY' config "
"var to be set")
DebugToolbar.load_panels(app)
app.before_request(self.process_request)
app.after_request(self.process_response)
app.teardown_request(self.teardown_request)
# Monkey-patch the Flask.dispatch_request method
app.dispatch_request = self.dispatch_request
app.add_url_rule('/_debug_toolbar/static/<path:filename>',
'_debug_toolbar.static', self.send_static_file)
app.register_blueprint(module, url_prefix='/_debug_toolbar/views')
| (self, app) |
37,437 | flask_debugtoolbar | process_request | null | def process_request(self):
g.debug_toolbar = self
if not self._show_toolbar():
return
real_request = request._get_current_object()
self.debug_toolbars_var.set({})
self.debug_toolbars_var.get()[real_request] = (
DebugToolbar(real_request, self.jinja_env))
for panel in self.debug_toolbars_var.get()[real_request].panels:
panel.process_request(real_request)
| (self) |
37,438 | flask_debugtoolbar | process_response | null | def process_response(self, response):
real_request = request._get_current_object()
if real_request not in self.debug_toolbars_var.get({}):
return response
# Intercept http redirect codes and display an html page with a
# link to the target.
if current_app.config['DEBUG_TB_INTERCEPT_REDIRECTS']:
if response.status_code in self._redirect_codes:
redirect_to = response.location
redirect_code = response.status_code
if redirect_to:
content = self.render('redirect.html', {
'redirect_to': redirect_to,
'redirect_code': redirect_code
})
response.content_length = len(content)
response.location = None
response.response = [content]
response.status_code = 200
# If the http response code is an allowed code then we process to add the
# toolbar to the returned html response.
if not (response.status_code in self._toolbar_codes and
response.is_sequence and
response.headers['content-type'].startswith('text/html')):
return response
content_encoding = response.headers.get('Content-Encoding')
if content_encoding and 'gzip' in content_encoding:
response_html = gzip_decompress(response.data).decode()
else:
response_html = response.get_data(as_text=True)
no_case = response_html.lower()
body_end = no_case.rfind('</body>')
if body_end >= 0:
before = response_html[:body_end]
after = response_html[body_end:]
elif no_case.startswith('<!doctype html>'):
before = response_html
after = ''
else:
warnings.warn('Could not insert debug toolbar.'
' </body> tag not found in response.')
return response
toolbar = self.debug_toolbars_var.get()[real_request]
for panel in toolbar.panels:
panel.process_response(real_request, response)
toolbar_html = toolbar.render_toolbar()
content = ''.join((before, toolbar_html, after))
content = content.encode('utf-8')
if content_encoding and 'gzip' in content_encoding:
content = gzip_compress(content)
response.response = [content]
response.content_length = len(content)
return response
| (self, response) |
37,439 | flask_debugtoolbar | process_view | This method is called just before the flask view is called.
This is done by the dispatch_request method.
| def process_view(self, app, view_func, view_kwargs):
""" This method is called just before the flask view is called.
This is done by the dispatch_request method.
"""
real_request = request._get_current_object()
try:
toolbar = self.debug_toolbars_var.get({})[real_request]
except KeyError:
return view_func
for panel in toolbar.panels:
new_view = panel.process_view(real_request, view_func, view_kwargs)
if new_view:
view_func = new_view
return view_func
| (self, app, view_func, view_kwargs) |
37,440 | flask_debugtoolbar | render | null | def render(self, template_name, context):
template = self.jinja_env.get_template(template_name)
return template.render(**context)
| (self, template_name, context) |
37,441 | flask_debugtoolbar | send_static_file | Send a static file from the flask-debugtoolbar static directory. | def send_static_file(self, filename):
"""Send a static file from the flask-debugtoolbar static directory."""
return send_from_directory(self._static_dir, filename)
| (self, filename) |
37,442 | flask_debugtoolbar | teardown_request | null | def teardown_request(self, exc):
# debug_toolbars_var won't be set under `flask.copy_current_request_context`
self.debug_toolbars_var.get({}).pop(request._get_current_object(), None)
| (self, exc) |
37,443 | jinja2.environment | Environment | The core component of Jinja is the `Environment`. It contains
important shared variables like configuration, filters, tests,
globals and others. Instances of this class may be modified if
they are not shared and if no template was loaded so far.
Modifications on environments after the first template was loaded
will lead to surprising effects and undefined behavior.
Here are the possible initialization parameters:
`block_start_string`
The string marking the beginning of a block. Defaults to ``'{%'``.
`block_end_string`
The string marking the end of a block. Defaults to ``'%}'``.
`variable_start_string`
The string marking the beginning of a print statement.
Defaults to ``'{{'``.
`variable_end_string`
The string marking the end of a print statement. Defaults to
``'}}'``.
`comment_start_string`
The string marking the beginning of a comment. Defaults to ``'{#'``.
`comment_end_string`
The string marking the end of a comment. Defaults to ``'#}'``.
`line_statement_prefix`
If given and a string, this will be used as prefix for line based
statements. See also :ref:`line-statements`.
`line_comment_prefix`
If given and a string, this will be used as prefix for line based
comments. See also :ref:`line-statements`.
.. versionadded:: 2.2
`trim_blocks`
If this is set to ``True`` the first newline after a block is
removed (block, not variable tag!). Defaults to `False`.
`lstrip_blocks`
If this is set to ``True`` leading spaces and tabs are stripped
from the start of a line to a block. Defaults to `False`.
`newline_sequence`
The sequence that starts a newline. Must be one of ``'\r'``,
``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
useful default for Linux and OS X systems as well as web
applications.
`keep_trailing_newline`
Preserve the trailing newline when rendering templates.
The default is ``False``, which causes a single newline,
if present, to be stripped from the end of the template.
.. versionadded:: 2.7
`extensions`
List of Jinja extensions to use. This can either be import paths
as strings or extension classes. For more information have a
look at :ref:`the extensions documentation <jinja-extensions>`.
`optimized`
should the optimizer be enabled? Default is ``True``.
`undefined`
:class:`Undefined` or a subclass of it that is used to represent
undefined values in the template.
`finalize`
A callable that can be used to process the result of a variable
expression before it is output. For example one can convert
``None`` implicitly into an empty string here.
`autoescape`
If set to ``True`` the XML/HTML autoescaping feature is enabled by
default. For more details about autoescaping see
:class:`~markupsafe.Markup`. As of Jinja 2.4 this can also
be a callable that is passed the template name and has to
return ``True`` or ``False`` depending on autoescape should be
enabled by default.
.. versionchanged:: 2.4
`autoescape` can now be a function
`loader`
The template loader for this environment.
`cache_size`
The size of the cache. Per default this is ``400`` which means
that if more than 400 templates are loaded the loader will clean
out the least recently used template. If the cache size is set to
``0`` templates are recompiled all the time, if the cache size is
``-1`` the cache will not be cleaned.
.. versionchanged:: 2.8
The cache size was increased to 400 from a low 50.
`auto_reload`
Some loaders load templates from locations where the template
sources may change (ie: file system or database). If
``auto_reload`` is set to ``True`` (default) every time a template is
requested the loader checks if the source changed and if yes, it
will reload the template. For higher performance it's possible to
disable that.
`bytecode_cache`
If set to a bytecode cache object, this object will provide a
cache for the internal Jinja bytecode so that templates don't
have to be parsed if they were not changed.
See :ref:`bytecode-cache` for more information.
`enable_async`
If set to true this enables async template execution which
allows using async functions and generators.
| class Environment:
r"""The core component of Jinja is the `Environment`. It contains
important shared variables like configuration, filters, tests,
globals and others. Instances of this class may be modified if
they are not shared and if no template was loaded so far.
Modifications on environments after the first template was loaded
will lead to surprising effects and undefined behavior.
Here are the possible initialization parameters:
`block_start_string`
The string marking the beginning of a block. Defaults to ``'{%'``.
`block_end_string`
The string marking the end of a block. Defaults to ``'%}'``.
`variable_start_string`
The string marking the beginning of a print statement.
Defaults to ``'{{'``.
`variable_end_string`
The string marking the end of a print statement. Defaults to
``'}}'``.
`comment_start_string`
The string marking the beginning of a comment. Defaults to ``'{#'``.
`comment_end_string`
The string marking the end of a comment. Defaults to ``'#}'``.
`line_statement_prefix`
If given and a string, this will be used as prefix for line based
statements. See also :ref:`line-statements`.
`line_comment_prefix`
If given and a string, this will be used as prefix for line based
comments. See also :ref:`line-statements`.
.. versionadded:: 2.2
`trim_blocks`
If this is set to ``True`` the first newline after a block is
removed (block, not variable tag!). Defaults to `False`.
`lstrip_blocks`
If this is set to ``True`` leading spaces and tabs are stripped
from the start of a line to a block. Defaults to `False`.
`newline_sequence`
The sequence that starts a newline. Must be one of ``'\r'``,
``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
useful default for Linux and OS X systems as well as web
applications.
`keep_trailing_newline`
Preserve the trailing newline when rendering templates.
The default is ``False``, which causes a single newline,
if present, to be stripped from the end of the template.
.. versionadded:: 2.7
`extensions`
List of Jinja extensions to use. This can either be import paths
as strings or extension classes. For more information have a
look at :ref:`the extensions documentation <jinja-extensions>`.
`optimized`
should the optimizer be enabled? Default is ``True``.
`undefined`
:class:`Undefined` or a subclass of it that is used to represent
undefined values in the template.
`finalize`
A callable that can be used to process the result of a variable
expression before it is output. For example one can convert
``None`` implicitly into an empty string here.
`autoescape`
If set to ``True`` the XML/HTML autoescaping feature is enabled by
default. For more details about autoescaping see
:class:`~markupsafe.Markup`. As of Jinja 2.4 this can also
be a callable that is passed the template name and has to
return ``True`` or ``False`` depending on autoescape should be
enabled by default.
.. versionchanged:: 2.4
`autoescape` can now be a function
`loader`
The template loader for this environment.
`cache_size`
The size of the cache. Per default this is ``400`` which means
that if more than 400 templates are loaded the loader will clean
out the least recently used template. If the cache size is set to
``0`` templates are recompiled all the time, if the cache size is
``-1`` the cache will not be cleaned.
.. versionchanged:: 2.8
The cache size was increased to 400 from a low 50.
`auto_reload`
Some loaders load templates from locations where the template
sources may change (ie: file system or database). If
``auto_reload`` is set to ``True`` (default) every time a template is
requested the loader checks if the source changed and if yes, it
will reload the template. For higher performance it's possible to
disable that.
`bytecode_cache`
If set to a bytecode cache object, this object will provide a
cache for the internal Jinja bytecode so that templates don't
have to be parsed if they were not changed.
See :ref:`bytecode-cache` for more information.
`enable_async`
If set to true this enables async template execution which
allows using async functions and generators.
"""
#: if this environment is sandboxed. Modifying this variable won't make
#: the environment sandboxed though. For a real sandboxed environment
#: have a look at jinja2.sandbox. This flag alone controls the code
#: generation by the compiler.
sandboxed = False
#: True if the environment is just an overlay
overlayed = False
#: the environment this environment is linked to if it is an overlay
linked_to: t.Optional["Environment"] = None
#: shared environments have this set to `True`. A shared environment
#: must not be modified
shared = False
#: the class that is used for code generation. See
#: :class:`~jinja2.compiler.CodeGenerator` for more information.
code_generator_class: t.Type["CodeGenerator"] = CodeGenerator
concat = "".join
#: the context class that is used for templates. See
#: :class:`~jinja2.runtime.Context` for more information.
context_class: t.Type[Context] = Context
template_class: t.Type["Template"]
def __init__(
self,
block_start_string: str = BLOCK_START_STRING,
block_end_string: str = BLOCK_END_STRING,
variable_start_string: str = VARIABLE_START_STRING,
variable_end_string: str = VARIABLE_END_STRING,
comment_start_string: str = COMMENT_START_STRING,
comment_end_string: str = COMMENT_END_STRING,
line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX,
line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX,
trim_blocks: bool = TRIM_BLOCKS,
lstrip_blocks: bool = LSTRIP_BLOCKS,
newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,
keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,
extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (),
optimized: bool = True,
undefined: t.Type[Undefined] = Undefined,
finalize: t.Optional[t.Callable[..., t.Any]] = None,
autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False,
loader: t.Optional["BaseLoader"] = None,
cache_size: int = 400,
auto_reload: bool = True,
bytecode_cache: t.Optional["BytecodeCache"] = None,
enable_async: bool = False,
):
# !!Important notice!!
# The constructor accepts quite a few arguments that should be
# passed by keyword rather than position. However it's important to
# not change the order of arguments because it's used at least
# internally in those cases:
# - spontaneous environments (i18n extension and Template)
# - unittests
# If parameter changes are required only add parameters at the end
# and don't change the arguments (or the defaults!) of the arguments
# existing already.
# lexer / parser information
self.block_start_string = block_start_string
self.block_end_string = block_end_string
self.variable_start_string = variable_start_string
self.variable_end_string = variable_end_string
self.comment_start_string = comment_start_string
self.comment_end_string = comment_end_string
self.line_statement_prefix = line_statement_prefix
self.line_comment_prefix = line_comment_prefix
self.trim_blocks = trim_blocks
self.lstrip_blocks = lstrip_blocks
self.newline_sequence = newline_sequence
self.keep_trailing_newline = keep_trailing_newline
# runtime information
self.undefined: t.Type[Undefined] = undefined
self.optimized = optimized
self.finalize = finalize
self.autoescape = autoescape
# defaults
self.filters = DEFAULT_FILTERS.copy()
self.tests = DEFAULT_TESTS.copy()
self.globals = DEFAULT_NAMESPACE.copy()
# set the loader provided
self.loader = loader
self.cache = create_cache(cache_size)
self.bytecode_cache = bytecode_cache
self.auto_reload = auto_reload
# configurable policies
self.policies = DEFAULT_POLICIES.copy()
# load extensions
self.extensions = load_extensions(self, extensions)
self.is_async = enable_async
_environment_config_check(self)
def add_extension(self, extension: t.Union[str, t.Type["Extension"]]) -> None:
"""Adds an extension after the environment was created.
.. versionadded:: 2.5
"""
self.extensions.update(load_extensions(self, [extension]))
def extend(self, **attributes: t.Any) -> None:
"""Add the items to the instance of the environment if they do not exist
yet. This is used by :ref:`extensions <writing-extensions>` to register
callbacks and configuration values without breaking inheritance.
"""
for key, value in attributes.items():
if not hasattr(self, key):
setattr(self, key, value)
def overlay(
self,
block_start_string: str = missing,
block_end_string: str = missing,
variable_start_string: str = missing,
variable_end_string: str = missing,
comment_start_string: str = missing,
comment_end_string: str = missing,
line_statement_prefix: t.Optional[str] = missing,
line_comment_prefix: t.Optional[str] = missing,
trim_blocks: bool = missing,
lstrip_blocks: bool = missing,
newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = missing,
keep_trailing_newline: bool = missing,
extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = missing,
optimized: bool = missing,
undefined: t.Type[Undefined] = missing,
finalize: t.Optional[t.Callable[..., t.Any]] = missing,
autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = missing,
loader: t.Optional["BaseLoader"] = missing,
cache_size: int = missing,
auto_reload: bool = missing,
bytecode_cache: t.Optional["BytecodeCache"] = missing,
enable_async: bool = False,
) -> "Environment":
"""Create a new overlay environment that shares all the data with the
current environment except for cache and the overridden attributes.
Extensions cannot be removed for an overlayed environment. An overlayed
environment automatically gets all the extensions of the environment it
is linked to plus optional extra extensions.
Creating overlays should happen after the initial environment was set
up completely. Not all attributes are truly linked, some are just
copied over so modifications on the original environment may not shine
through.
.. versionchanged:: 3.1.2
Added the ``newline_sequence``,, ``keep_trailing_newline``,
and ``enable_async`` parameters to match ``__init__``.
"""
args = dict(locals())
del args["self"], args["cache_size"], args["extensions"], args["enable_async"]
rv = object.__new__(self.__class__)
rv.__dict__.update(self.__dict__)
rv.overlayed = True
rv.linked_to = self
for key, value in args.items():
if value is not missing:
setattr(rv, key, value)
if cache_size is not missing:
rv.cache = create_cache(cache_size)
else:
rv.cache = copy_cache(self.cache)
rv.extensions = {}
for key, value in self.extensions.items():
rv.extensions[key] = value.bind(rv)
if extensions is not missing:
rv.extensions.update(load_extensions(rv, extensions))
if enable_async is not missing:
rv.is_async = enable_async
return _environment_config_check(rv)
@property
def lexer(self) -> Lexer:
"""The lexer for this environment."""
return get_lexer(self)
def iter_extensions(self) -> t.Iterator["Extension"]:
"""Iterates over the extensions by priority."""
return iter(sorted(self.extensions.values(), key=lambda x: x.priority))
def getitem(
self, obj: t.Any, argument: t.Union[str, t.Any]
) -> t.Union[t.Any, Undefined]:
"""Get an item or attribute of an object but prefer the item."""
try:
return obj[argument]
except (AttributeError, TypeError, LookupError):
if isinstance(argument, str):
try:
attr = str(argument)
except Exception:
pass
else:
try:
return getattr(obj, attr)
except AttributeError:
pass
return self.undefined(obj=obj, name=argument)
def getattr(self, obj: t.Any, attribute: str) -> t.Any:
"""Get an item or attribute of an object but prefer the attribute.
Unlike :meth:`getitem` the attribute *must* be a string.
"""
try:
return getattr(obj, attribute)
except AttributeError:
pass
try:
return obj[attribute]
except (TypeError, LookupError, AttributeError):
return self.undefined(obj=obj, name=attribute)
def _filter_test_common(
self,
name: t.Union[str, Undefined],
value: t.Any,
args: t.Optional[t.Sequence[t.Any]],
kwargs: t.Optional[t.Mapping[str, t.Any]],
context: t.Optional[Context],
eval_ctx: t.Optional[EvalContext],
is_filter: bool,
) -> t.Any:
if is_filter:
env_map = self.filters
type_name = "filter"
else:
env_map = self.tests
type_name = "test"
func = env_map.get(name) # type: ignore
if func is None:
msg = f"No {type_name} named {name!r}."
if isinstance(name, Undefined):
try:
name._fail_with_undefined_error()
except Exception as e:
msg = f"{msg} ({e}; did you forget to quote the callable name?)"
raise TemplateRuntimeError(msg)
args = [value, *(args if args is not None else ())]
kwargs = kwargs if kwargs is not None else {}
pass_arg = _PassArg.from_obj(func)
if pass_arg is _PassArg.context:
if context is None:
raise TemplateRuntimeError(
f"Attempted to invoke a context {type_name} without context."
)
args.insert(0, context)
elif pass_arg is _PassArg.eval_context:
if eval_ctx is None:
if context is not None:
eval_ctx = context.eval_ctx
else:
eval_ctx = EvalContext(self)
args.insert(0, eval_ctx)
elif pass_arg is _PassArg.environment:
args.insert(0, self)
return func(*args, **kwargs)
def call_filter(
self,
name: str,
value: t.Any,
args: t.Optional[t.Sequence[t.Any]] = None,
kwargs: t.Optional[t.Mapping[str, t.Any]] = None,
context: t.Optional[Context] = None,
eval_ctx: t.Optional[EvalContext] = None,
) -> t.Any:
"""Invoke a filter on a value the same way the compiler does.
This might return a coroutine if the filter is running from an
environment in async mode and the filter supports async
execution. It's your responsibility to await this if needed.
.. versionadded:: 2.7
"""
return self._filter_test_common(
name, value, args, kwargs, context, eval_ctx, True
)
def call_test(
self,
name: str,
value: t.Any,
args: t.Optional[t.Sequence[t.Any]] = None,
kwargs: t.Optional[t.Mapping[str, t.Any]] = None,
context: t.Optional[Context] = None,
eval_ctx: t.Optional[EvalContext] = None,
) -> t.Any:
"""Invoke a test on a value the same way the compiler does.
This might return a coroutine if the test is running from an
environment in async mode and the test supports async execution.
It's your responsibility to await this if needed.
.. versionchanged:: 3.0
Tests support ``@pass_context``, etc. decorators. Added
the ``context`` and ``eval_ctx`` parameters.
.. versionadded:: 2.7
"""
return self._filter_test_common(
name, value, args, kwargs, context, eval_ctx, False
)
@internalcode
def parse(
self,
source: str,
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
) -> nodes.Template:
"""Parse the sourcecode and return the abstract syntax tree. This
tree of nodes is used by the compiler to convert the template into
executable source- or bytecode. This is useful for debugging or to
extract information from templates.
If you are :ref:`developing Jinja extensions <writing-extensions>`
this gives you a good overview of the node tree generated.
"""
try:
return self._parse(source, name, filename)
except TemplateSyntaxError:
self.handle_exception(source=source)
def _parse(
self, source: str, name: t.Optional[str], filename: t.Optional[str]
) -> nodes.Template:
"""Internal parsing function used by `parse` and `compile`."""
return Parser(self, source, name, filename).parse()
def lex(
self,
source: str,
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
) -> t.Iterator[t.Tuple[int, str, str]]:
"""Lex the given sourcecode and return a generator that yields
tokens as tuples in the form ``(lineno, token_type, value)``.
This can be useful for :ref:`extension development <writing-extensions>`
and debugging templates.
This does not perform preprocessing. If you want the preprocessing
of the extensions to be applied you have to filter source through
the :meth:`preprocess` method.
"""
source = str(source)
try:
return self.lexer.tokeniter(source, name, filename)
except TemplateSyntaxError:
self.handle_exception(source=source)
def preprocess(
self,
source: str,
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
) -> str:
"""Preprocesses the source with all extensions. This is automatically
called for all parsing and compiling methods but *not* for :meth:`lex`
because there you usually only want the actual source tokenized.
"""
return reduce(
lambda s, e: e.preprocess(s, name, filename),
self.iter_extensions(),
str(source),
)
def _tokenize(
self,
source: str,
name: t.Optional[str],
filename: t.Optional[str] = None,
state: t.Optional[str] = None,
) -> TokenStream:
"""Called by the parser to do the preprocessing and filtering
for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
"""
source = self.preprocess(source, name, filename)
stream = self.lexer.tokenize(source, name, filename, state)
for ext in self.iter_extensions():
stream = ext.filter_stream(stream) # type: ignore
if not isinstance(stream, TokenStream):
stream = TokenStream(stream, name, filename)
return stream
def _generate(
self,
source: nodes.Template,
name: t.Optional[str],
filename: t.Optional[str],
defer_init: bool = False,
) -> str:
"""Internal hook that can be overridden to hook a different generate
method in.
.. versionadded:: 2.5
"""
return generate( # type: ignore
source,
self,
name,
filename,
defer_init=defer_init,
optimized=self.optimized,
)
def _compile(self, source: str, filename: str) -> CodeType:
"""Internal hook that can be overridden to hook a different compile
method in.
.. versionadded:: 2.5
"""
return compile(source, filename, "exec")
@typing.overload
def compile( # type: ignore
self,
source: t.Union[str, nodes.Template],
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
raw: "te.Literal[False]" = False,
defer_init: bool = False,
) -> CodeType: ...
@typing.overload
def compile(
self,
source: t.Union[str, nodes.Template],
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
raw: "te.Literal[True]" = ...,
defer_init: bool = False,
) -> str: ...
@internalcode
def compile(
self,
source: t.Union[str, nodes.Template],
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
raw: bool = False,
defer_init: bool = False,
) -> t.Union[str, CodeType]:
"""Compile a node or template source code. The `name` parameter is
the load name of the template after it was joined using
:meth:`join_path` if necessary, not the filename on the file system.
the `filename` parameter is the estimated filename of the template on
the file system. If the template came from a database or memory this
can be omitted.
The return value of this method is a python code object. If the `raw`
parameter is `True` the return value will be a string with python
code equivalent to the bytecode returned otherwise. This method is
mainly used internally.
`defer_init` is use internally to aid the module code generator. This
causes the generated code to be able to import without the global
environment variable to be set.
.. versionadded:: 2.4
`defer_init` parameter added.
"""
source_hint = None
try:
if isinstance(source, str):
source_hint = source
source = self._parse(source, name, filename)
source = self._generate(source, name, filename, defer_init=defer_init)
if raw:
return source
if filename is None:
filename = "<template>"
return self._compile(source, filename)
except TemplateSyntaxError:
self.handle_exception(source=source_hint)
def compile_expression(
self, source: str, undefined_to_none: bool = True
) -> "TemplateExpression":
"""A handy helper method that returns a callable that accepts keyword
arguments that appear as variables in the expression. If called it
returns the result of the expression.
This is useful if applications want to use the same rules as Jinja
in template "configuration files" or similar situations.
Example usage:
>>> env = Environment()
>>> expr = env.compile_expression('foo == 42')
>>> expr(foo=23)
False
>>> expr(foo=42)
True
Per default the return value is converted to `None` if the
expression returns an undefined value. This can be changed
by setting `undefined_to_none` to `False`.
>>> env.compile_expression('var')() is None
True
>>> env.compile_expression('var', undefined_to_none=False)()
Undefined
.. versionadded:: 2.1
"""
parser = Parser(self, source, state="variable")
try:
expr = parser.parse_expression()
if not parser.stream.eos:
raise TemplateSyntaxError(
"chunk after expression", parser.stream.current.lineno, None, None
)
expr.set_environment(self)
except TemplateSyntaxError:
self.handle_exception(source=source)
body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)]
template = self.from_string(nodes.Template(body, lineno=1))
return TemplateExpression(template, undefined_to_none)
def compile_templates(
self,
target: t.Union[str, "os.PathLike[str]"],
extensions: t.Optional[t.Collection[str]] = None,
filter_func: t.Optional[t.Callable[[str], bool]] = None,
zip: t.Optional[str] = "deflated",
log_function: t.Optional[t.Callable[[str], None]] = None,
ignore_errors: bool = True,
) -> None:
"""Finds all the templates the loader can find, compiles them
and stores them in `target`. If `zip` is `None`, instead of in a
zipfile, the templates will be stored in a directory.
By default a deflate zip algorithm is used. To switch to
the stored algorithm, `zip` can be set to ``'stored'``.
`extensions` and `filter_func` are passed to :meth:`list_templates`.
Each template returned will be compiled to the target folder or
zipfile.
By default template compilation errors are ignored. In case a
log function is provided, errors are logged. If you want template
syntax errors to abort the compilation you can set `ignore_errors`
to `False` and you will get an exception on syntax errors.
.. versionadded:: 2.4
"""
from .loaders import ModuleLoader
if log_function is None:
def log_function(x: str) -> None:
pass
assert log_function is not None
assert self.loader is not None, "No loader configured."
def write_file(filename: str, data: str) -> None:
if zip:
info = ZipInfo(filename)
info.external_attr = 0o755 << 16
zip_file.writestr(info, data)
else:
with open(os.path.join(target, filename), "wb") as f:
f.write(data.encode("utf8"))
if zip is not None:
from zipfile import ZIP_DEFLATED
from zipfile import ZIP_STORED
from zipfile import ZipFile
from zipfile import ZipInfo
zip_file = ZipFile(
target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]
)
log_function(f"Compiling into Zip archive {target!r}")
else:
if not os.path.isdir(target):
os.makedirs(target)
log_function(f"Compiling into folder {target!r}")
try:
for name in self.list_templates(extensions, filter_func):
source, filename, _ = self.loader.get_source(self, name)
try:
code = self.compile(source, name, filename, True, True)
except TemplateSyntaxError as e:
if not ignore_errors:
raise
log_function(f'Could not compile "{name}": {e}')
continue
filename = ModuleLoader.get_module_filename(name)
write_file(filename, code)
log_function(f'Compiled "{name}" as {filename}')
finally:
if zip:
zip_file.close()
log_function("Finished compiling templates")
def list_templates(
self,
extensions: t.Optional[t.Collection[str]] = None,
filter_func: t.Optional[t.Callable[[str], bool]] = None,
) -> t.List[str]:
"""Returns a list of templates for this environment. This requires
that the loader supports the loader's
:meth:`~BaseLoader.list_templates` method.
If there are other files in the template folder besides the
actual templates, the returned list can be filtered. There are two
ways: either `extensions` is set to a list of file extensions for
templates, or a `filter_func` can be provided which is a callable that
is passed a template name and should return `True` if it should end up
in the result list.
If the loader does not support that, a :exc:`TypeError` is raised.
.. versionadded:: 2.4
"""
assert self.loader is not None, "No loader configured."
names = self.loader.list_templates()
if extensions is not None:
if filter_func is not None:
raise TypeError(
"either extensions or filter_func can be passed, but not both"
)
def filter_func(x: str) -> bool:
return "." in x and x.rsplit(".", 1)[1] in extensions
if filter_func is not None:
names = [name for name in names if filter_func(name)]
return names
def handle_exception(self, source: t.Optional[str] = None) -> "te.NoReturn":
"""Exception handling helper. This is used internally to either raise
rewritten exceptions or return a rendered traceback for the template.
"""
from .debug import rewrite_traceback_stack
raise rewrite_traceback_stack(source=source)
def join_path(self, template: str, parent: str) -> str:
"""Join a template with the parent. By default all the lookups are
relative to the loader root so this method returns the `template`
parameter unchanged, but if the paths should be relative to the
parent template, this function can be used to calculate the real
template name.
Subclasses may override this method and implement template path
joining here.
"""
return template
@internalcode
def _load_template(
self, name: str, globals: t.Optional[t.MutableMapping[str, t.Any]]
) -> "Template":
if self.loader is None:
raise TypeError("no loader for this environment specified")
cache_key = (weakref.ref(self.loader), name)
if self.cache is not None:
template = self.cache.get(cache_key)
if template is not None and (
not self.auto_reload or template.is_up_to_date
):
# template.globals is a ChainMap, modifying it will only
# affect the template, not the environment globals.
if globals:
template.globals.update(globals)
return template
template = self.loader.load(self, name, self.make_globals(globals))
if self.cache is not None:
self.cache[cache_key] = template
return template
@internalcode
def get_template(
self,
name: t.Union[str, "Template"],
parent: t.Optional[str] = None,
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
) -> "Template":
"""Load a template by name with :attr:`loader` and return a
:class:`Template`. If the template does not exist a
:exc:`TemplateNotFound` exception is raised.
:param name: Name of the template to load. When loading
templates from the filesystem, "/" is used as the path
separator, even on Windows.
:param parent: The name of the parent template importing this
template. :meth:`join_path` can be used to implement name
transformations with this.
:param globals: Extend the environment :attr:`globals` with
these extra variables available for all renders of this
template. If the template has already been loaded and
cached, its globals are updated with any new items.
.. versionchanged:: 3.0
If a template is loaded from cache, ``globals`` will update
the template's globals instead of ignoring the new values.
.. versionchanged:: 2.4
If ``name`` is a :class:`Template` object it is returned
unchanged.
"""
if isinstance(name, Template):
return name
if parent is not None:
name = self.join_path(name, parent)
return self._load_template(name, globals)
@internalcode
def select_template(
self,
names: t.Iterable[t.Union[str, "Template"]],
parent: t.Optional[str] = None,
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
) -> "Template":
"""Like :meth:`get_template`, but tries loading multiple names.
If none of the names can be loaded a :exc:`TemplatesNotFound`
exception is raised.
:param names: List of template names to try loading in order.
:param parent: The name of the parent template importing this
template. :meth:`join_path` can be used to implement name
transformations with this.
:param globals: Extend the environment :attr:`globals` with
these extra variables available for all renders of this
template. If the template has already been loaded and
cached, its globals are updated with any new items.
.. versionchanged:: 3.0
If a template is loaded from cache, ``globals`` will update
the template's globals instead of ignoring the new values.
.. versionchanged:: 2.11
If ``names`` is :class:`Undefined`, an :exc:`UndefinedError`
is raised instead. If no templates were found and ``names``
contains :class:`Undefined`, the message is more helpful.
.. versionchanged:: 2.4
If ``names`` contains a :class:`Template` object it is
returned unchanged.
.. versionadded:: 2.3
"""
if isinstance(names, Undefined):
names._fail_with_undefined_error()
if not names:
raise TemplatesNotFound(
message="Tried to select from an empty list of templates."
)
for name in names:
if isinstance(name, Template):
return name
if parent is not None:
name = self.join_path(name, parent)
try:
return self._load_template(name, globals)
except (TemplateNotFound, UndefinedError):
pass
raise TemplatesNotFound(names) # type: ignore
@internalcode
def get_or_select_template(
self,
template_name_or_list: t.Union[
str, "Template", t.List[t.Union[str, "Template"]]
],
parent: t.Optional[str] = None,
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
) -> "Template":
"""Use :meth:`select_template` if an iterable of template names
is given, or :meth:`get_template` if one name is given.
.. versionadded:: 2.3
"""
if isinstance(template_name_or_list, (str, Undefined)):
return self.get_template(template_name_or_list, parent, globals)
elif isinstance(template_name_or_list, Template):
return template_name_or_list
return self.select_template(template_name_or_list, parent, globals)
def from_string(
self,
source: t.Union[str, nodes.Template],
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
template_class: t.Optional[t.Type["Template"]] = None,
) -> "Template":
"""Load a template from a source string without using
:attr:`loader`.
:param source: Jinja source to compile into a template.
:param globals: Extend the environment :attr:`globals` with
these extra variables available for all renders of this
template. If the template has already been loaded and
cached, its globals are updated with any new items.
:param template_class: Return an instance of this
:class:`Template` class.
"""
gs = self.make_globals(globals)
cls = template_class or self.template_class
return cls.from_code(self, self.compile(source), gs, None)
def make_globals(
self, d: t.Optional[t.MutableMapping[str, t.Any]]
) -> t.MutableMapping[str, t.Any]:
"""Make the globals map for a template. Any given template
globals overlay the environment :attr:`globals`.
Returns a :class:`collections.ChainMap`. This allows any changes
to a template's globals to only affect that template, while
changes to the environment's globals are still reflected.
However, avoid modifying any globals after a template is loaded.
:param d: Dict of template-specific globals.
.. versionchanged:: 3.0
Use :class:`collections.ChainMap` to always prevent mutating
environment globals.
"""
if d is None:
d = {}
return ChainMap(d, self.globals)
| (block_start_string: str = '{%', block_end_string: str = '%}', variable_start_string: str = '{{', variable_end_string: str = '}}', comment_start_string: str = '{#', comment_end_string: str = '#}', line_statement_prefix: Optional[str] = None, line_comment_prefix: Optional[str] = None, trim_blocks: bool = False, lstrip_blocks: bool = False, newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = '\n', keep_trailing_newline: bool = False, extensions: Sequence[Union[str, Type[ForwardRef('Extension')]]] = (), optimized: bool = True, undefined: Type[jinja2.runtime.Undefined] = <class 'jinja2.runtime.Undefined'>, finalize: Optional[Callable[..., Any]] = None, autoescape: Union[bool, Callable[[Optional[str]], bool]] = False, loader: Optional[ForwardRef('BaseLoader')] = None, cache_size: int = 400, auto_reload: bool = True, bytecode_cache: Optional[ForwardRef('BytecodeCache')] = None, enable_async: bool = False) |
37,444 | jinja2.environment | __init__ | null | def __init__(
self,
block_start_string: str = BLOCK_START_STRING,
block_end_string: str = BLOCK_END_STRING,
variable_start_string: str = VARIABLE_START_STRING,
variable_end_string: str = VARIABLE_END_STRING,
comment_start_string: str = COMMENT_START_STRING,
comment_end_string: str = COMMENT_END_STRING,
line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX,
line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX,
trim_blocks: bool = TRIM_BLOCKS,
lstrip_blocks: bool = LSTRIP_BLOCKS,
newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,
keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,
extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (),
optimized: bool = True,
undefined: t.Type[Undefined] = Undefined,
finalize: t.Optional[t.Callable[..., t.Any]] = None,
autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False,
loader: t.Optional["BaseLoader"] = None,
cache_size: int = 400,
auto_reload: bool = True,
bytecode_cache: t.Optional["BytecodeCache"] = None,
enable_async: bool = False,
):
# !!Important notice!!
# The constructor accepts quite a few arguments that should be
# passed by keyword rather than position. However it's important to
# not change the order of arguments because it's used at least
# internally in those cases:
# - spontaneous environments (i18n extension and Template)
# - unittests
# If parameter changes are required only add parameters at the end
# and don't change the arguments (or the defaults!) of the arguments
# existing already.
# lexer / parser information
self.block_start_string = block_start_string
self.block_end_string = block_end_string
self.variable_start_string = variable_start_string
self.variable_end_string = variable_end_string
self.comment_start_string = comment_start_string
self.comment_end_string = comment_end_string
self.line_statement_prefix = line_statement_prefix
self.line_comment_prefix = line_comment_prefix
self.trim_blocks = trim_blocks
self.lstrip_blocks = lstrip_blocks
self.newline_sequence = newline_sequence
self.keep_trailing_newline = keep_trailing_newline
# runtime information
self.undefined: t.Type[Undefined] = undefined
self.optimized = optimized
self.finalize = finalize
self.autoescape = autoescape
# defaults
self.filters = DEFAULT_FILTERS.copy()
self.tests = DEFAULT_TESTS.copy()
self.globals = DEFAULT_NAMESPACE.copy()
# set the loader provided
self.loader = loader
self.cache = create_cache(cache_size)
self.bytecode_cache = bytecode_cache
self.auto_reload = auto_reload
# configurable policies
self.policies = DEFAULT_POLICIES.copy()
# load extensions
self.extensions = load_extensions(self, extensions)
self.is_async = enable_async
_environment_config_check(self)
| (self, block_start_string: str = '{%', block_end_string: str = '%}', variable_start_string: str = '{{', variable_end_string: str = '}}', comment_start_string: str = '{#', comment_end_string: str = '#}', line_statement_prefix: Optional[str] = None, line_comment_prefix: Optional[str] = None, trim_blocks: bool = False, lstrip_blocks: bool = False, newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = '\n', keep_trailing_newline: bool = False, extensions: Sequence[Union[str, Type[ForwardRef('Extension')]]] = (), optimized: bool = True, undefined: Type[jinja2.runtime.Undefined] = <class 'jinja2.runtime.Undefined'>, finalize: Optional[Callable[..., Any]] = None, autoescape: Union[bool, Callable[[Optional[str]], bool]] = False, loader: Optional[ForwardRef('BaseLoader')] = None, cache_size: int = 400, auto_reload: bool = True, bytecode_cache: Optional[ForwardRef('BytecodeCache')] = None, enable_async: bool = False) |
37,445 | jinja2.environment | _compile | Internal hook that can be overridden to hook a different compile
method in.
.. versionadded:: 2.5
| def _compile(self, source: str, filename: str) -> CodeType:
"""Internal hook that can be overridden to hook a different compile
method in.
.. versionadded:: 2.5
"""
return compile(source, filename, "exec")
| (self, source: str, filename: str) -> code |
37,446 | jinja2.environment | _filter_test_common | null | def _filter_test_common(
self,
name: t.Union[str, Undefined],
value: t.Any,
args: t.Optional[t.Sequence[t.Any]],
kwargs: t.Optional[t.Mapping[str, t.Any]],
context: t.Optional[Context],
eval_ctx: t.Optional[EvalContext],
is_filter: bool,
) -> t.Any:
if is_filter:
env_map = self.filters
type_name = "filter"
else:
env_map = self.tests
type_name = "test"
func = env_map.get(name) # type: ignore
if func is None:
msg = f"No {type_name} named {name!r}."
if isinstance(name, Undefined):
try:
name._fail_with_undefined_error()
except Exception as e:
msg = f"{msg} ({e}; did you forget to quote the callable name?)"
raise TemplateRuntimeError(msg)
args = [value, *(args if args is not None else ())]
kwargs = kwargs if kwargs is not None else {}
pass_arg = _PassArg.from_obj(func)
if pass_arg is _PassArg.context:
if context is None:
raise TemplateRuntimeError(
f"Attempted to invoke a context {type_name} without context."
)
args.insert(0, context)
elif pass_arg is _PassArg.eval_context:
if eval_ctx is None:
if context is not None:
eval_ctx = context.eval_ctx
else:
eval_ctx = EvalContext(self)
args.insert(0, eval_ctx)
elif pass_arg is _PassArg.environment:
args.insert(0, self)
return func(*args, **kwargs)
| (self, name: Union[str, jinja2.runtime.Undefined], value: Any, args: Optional[Sequence[Any]], kwargs: Optional[Mapping[str, Any]], context: Optional[jinja2.runtime.Context], eval_ctx: Optional[jinja2.nodes.EvalContext], is_filter: bool) -> Any |
37,447 | jinja2.environment | _generate | Internal hook that can be overridden to hook a different generate
method in.
.. versionadded:: 2.5
| def _generate(
self,
source: nodes.Template,
name: t.Optional[str],
filename: t.Optional[str],
defer_init: bool = False,
) -> str:
"""Internal hook that can be overridden to hook a different generate
method in.
.. versionadded:: 2.5
"""
return generate( # type: ignore
source,
self,
name,
filename,
defer_init=defer_init,
optimized=self.optimized,
)
| (self, source: jinja2.nodes.Template, name: Optional[str], filename: Optional[str], defer_init: bool = False) -> str |
37,448 | jinja2.environment | _load_template | null | @internalcode
def _load_template(
self, name: str, globals: t.Optional[t.MutableMapping[str, t.Any]]
) -> "Template":
if self.loader is None:
raise TypeError("no loader for this environment specified")
cache_key = (weakref.ref(self.loader), name)
if self.cache is not None:
template = self.cache.get(cache_key)
if template is not None and (
not self.auto_reload or template.is_up_to_date
):
# template.globals is a ChainMap, modifying it will only
# affect the template, not the environment globals.
if globals:
template.globals.update(globals)
return template
template = self.loader.load(self, name, self.make_globals(globals))
if self.cache is not None:
self.cache[cache_key] = template
return template
| (self, name: str, globals: Optional[MutableMapping[str, Any]]) -> jinja2.environment.Template |
37,449 | jinja2.environment | _parse | Internal parsing function used by `parse` and `compile`. | def _parse(
self, source: str, name: t.Optional[str], filename: t.Optional[str]
) -> nodes.Template:
"""Internal parsing function used by `parse` and `compile`."""
return Parser(self, source, name, filename).parse()
| (self, source: str, name: Optional[str], filename: Optional[str]) -> jinja2.nodes.Template |
37,450 | jinja2.environment | _tokenize | Called by the parser to do the preprocessing and filtering
for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
| def _tokenize(
self,
source: str,
name: t.Optional[str],
filename: t.Optional[str] = None,
state: t.Optional[str] = None,
) -> TokenStream:
"""Called by the parser to do the preprocessing and filtering
for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
"""
source = self.preprocess(source, name, filename)
stream = self.lexer.tokenize(source, name, filename, state)
for ext in self.iter_extensions():
stream = ext.filter_stream(stream) # type: ignore
if not isinstance(stream, TokenStream):
stream = TokenStream(stream, name, filename)
return stream
| (self, source: str, name: Optional[str], filename: Optional[str] = None, state: Optional[str] = None) -> jinja2.lexer.TokenStream |
37,451 | jinja2.environment | add_extension | Adds an extension after the environment was created.
.. versionadded:: 2.5
| def add_extension(self, extension: t.Union[str, t.Type["Extension"]]) -> None:
"""Adds an extension after the environment was created.
.. versionadded:: 2.5
"""
self.extensions.update(load_extensions(self, [extension]))
| (self, extension: Union[str, Type[ForwardRef('Extension')]]) -> None |
37,452 | jinja2.environment | call_filter | Invoke a filter on a value the same way the compiler does.
This might return a coroutine if the filter is running from an
environment in async mode and the filter supports async
execution. It's your responsibility to await this if needed.
.. versionadded:: 2.7
| def call_filter(
self,
name: str,
value: t.Any,
args: t.Optional[t.Sequence[t.Any]] = None,
kwargs: t.Optional[t.Mapping[str, t.Any]] = None,
context: t.Optional[Context] = None,
eval_ctx: t.Optional[EvalContext] = None,
) -> t.Any:
"""Invoke a filter on a value the same way the compiler does.
This might return a coroutine if the filter is running from an
environment in async mode and the filter supports async
execution. It's your responsibility to await this if needed.
.. versionadded:: 2.7
"""
return self._filter_test_common(
name, value, args, kwargs, context, eval_ctx, True
)
| (self, name: str, value: Any, args: Optional[Sequence[Any]] = None, kwargs: Optional[Mapping[str, Any]] = None, context: Optional[jinja2.runtime.Context] = None, eval_ctx: Optional[jinja2.nodes.EvalContext] = None) -> Any |
37,453 | jinja2.environment | call_test | Invoke a test on a value the same way the compiler does.
This might return a coroutine if the test is running from an
environment in async mode and the test supports async execution.
It's your responsibility to await this if needed.
.. versionchanged:: 3.0
Tests support ``@pass_context``, etc. decorators. Added
the ``context`` and ``eval_ctx`` parameters.
.. versionadded:: 2.7
| def call_test(
self,
name: str,
value: t.Any,
args: t.Optional[t.Sequence[t.Any]] = None,
kwargs: t.Optional[t.Mapping[str, t.Any]] = None,
context: t.Optional[Context] = None,
eval_ctx: t.Optional[EvalContext] = None,
) -> t.Any:
"""Invoke a test on a value the same way the compiler does.
This might return a coroutine if the test is running from an
environment in async mode and the test supports async execution.
It's your responsibility to await this if needed.
.. versionchanged:: 3.0
Tests support ``@pass_context``, etc. decorators. Added
the ``context`` and ``eval_ctx`` parameters.
.. versionadded:: 2.7
"""
return self._filter_test_common(
name, value, args, kwargs, context, eval_ctx, False
)
| (self, name: str, value: Any, args: Optional[Sequence[Any]] = None, kwargs: Optional[Mapping[str, Any]] = None, context: Optional[jinja2.runtime.Context] = None, eval_ctx: Optional[jinja2.nodes.EvalContext] = None) -> Any |
37,454 | jinja2.environment | compile | Compile a node or template source code. The `name` parameter is
the load name of the template after it was joined using
:meth:`join_path` if necessary, not the filename on the file system.
the `filename` parameter is the estimated filename of the template on
the file system. If the template came from a database or memory this
can be omitted.
The return value of this method is a python code object. If the `raw`
parameter is `True` the return value will be a string with python
code equivalent to the bytecode returned otherwise. This method is
mainly used internally.
`defer_init` is use internally to aid the module code generator. This
causes the generated code to be able to import without the global
environment variable to be set.
.. versionadded:: 2.4
`defer_init` parameter added.
| @internalcode
def compile(
self,
source: t.Union[str, nodes.Template],
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
raw: bool = False,
defer_init: bool = False,
) -> t.Union[str, CodeType]:
"""Compile a node or template source code. The `name` parameter is
the load name of the template after it was joined using
:meth:`join_path` if necessary, not the filename on the file system.
the `filename` parameter is the estimated filename of the template on
the file system. If the template came from a database or memory this
can be omitted.
The return value of this method is a python code object. If the `raw`
parameter is `True` the return value will be a string with python
code equivalent to the bytecode returned otherwise. This method is
mainly used internally.
`defer_init` is use internally to aid the module code generator. This
causes the generated code to be able to import without the global
environment variable to be set.
.. versionadded:: 2.4
`defer_init` parameter added.
"""
source_hint = None
try:
if isinstance(source, str):
source_hint = source
source = self._parse(source, name, filename)
source = self._generate(source, name, filename, defer_init=defer_init)
if raw:
return source
if filename is None:
filename = "<template>"
return self._compile(source, filename)
except TemplateSyntaxError:
self.handle_exception(source=source_hint)
| (self, source: Union[str, jinja2.nodes.Template], name: Optional[str] = None, filename: Optional[str] = None, raw: bool = False, defer_init: bool = False) -> Union[str, code] |
37,455 | jinja2.environment | compile_expression | A handy helper method that returns a callable that accepts keyword
arguments that appear as variables in the expression. If called it
returns the result of the expression.
This is useful if applications want to use the same rules as Jinja
in template "configuration files" or similar situations.
Example usage:
>>> env = Environment()
>>> expr = env.compile_expression('foo == 42')
>>> expr(foo=23)
False
>>> expr(foo=42)
True
Per default the return value is converted to `None` if the
expression returns an undefined value. This can be changed
by setting `undefined_to_none` to `False`.
>>> env.compile_expression('var')() is None
True
>>> env.compile_expression('var', undefined_to_none=False)()
Undefined
.. versionadded:: 2.1
| def compile_expression(
self, source: str, undefined_to_none: bool = True
) -> "TemplateExpression":
"""A handy helper method that returns a callable that accepts keyword
arguments that appear as variables in the expression. If called it
returns the result of the expression.
This is useful if applications want to use the same rules as Jinja
in template "configuration files" or similar situations.
Example usage:
>>> env = Environment()
>>> expr = env.compile_expression('foo == 42')
>>> expr(foo=23)
False
>>> expr(foo=42)
True
Per default the return value is converted to `None` if the
expression returns an undefined value. This can be changed
by setting `undefined_to_none` to `False`.
>>> env.compile_expression('var')() is None
True
>>> env.compile_expression('var', undefined_to_none=False)()
Undefined
.. versionadded:: 2.1
"""
parser = Parser(self, source, state="variable")
try:
expr = parser.parse_expression()
if not parser.stream.eos:
raise TemplateSyntaxError(
"chunk after expression", parser.stream.current.lineno, None, None
)
expr.set_environment(self)
except TemplateSyntaxError:
self.handle_exception(source=source)
body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)]
template = self.from_string(nodes.Template(body, lineno=1))
return TemplateExpression(template, undefined_to_none)
| (self, source: str, undefined_to_none: bool = True) -> jinja2.environment.TemplateExpression |
37,456 | jinja2.environment | compile_templates | Finds all the templates the loader can find, compiles them
and stores them in `target`. If `zip` is `None`, instead of in a
zipfile, the templates will be stored in a directory.
By default a deflate zip algorithm is used. To switch to
the stored algorithm, `zip` can be set to ``'stored'``.
`extensions` and `filter_func` are passed to :meth:`list_templates`.
Each template returned will be compiled to the target folder or
zipfile.
By default template compilation errors are ignored. In case a
log function is provided, errors are logged. If you want template
syntax errors to abort the compilation you can set `ignore_errors`
to `False` and you will get an exception on syntax errors.
.. versionadded:: 2.4
| def compile_templates(
self,
target: t.Union[str, "os.PathLike[str]"],
extensions: t.Optional[t.Collection[str]] = None,
filter_func: t.Optional[t.Callable[[str], bool]] = None,
zip: t.Optional[str] = "deflated",
log_function: t.Optional[t.Callable[[str], None]] = None,
ignore_errors: bool = True,
) -> None:
"""Finds all the templates the loader can find, compiles them
and stores them in `target`. If `zip` is `None`, instead of in a
zipfile, the templates will be stored in a directory.
By default a deflate zip algorithm is used. To switch to
the stored algorithm, `zip` can be set to ``'stored'``.
`extensions` and `filter_func` are passed to :meth:`list_templates`.
Each template returned will be compiled to the target folder or
zipfile.
By default template compilation errors are ignored. In case a
log function is provided, errors are logged. If you want template
syntax errors to abort the compilation you can set `ignore_errors`
to `False` and you will get an exception on syntax errors.
.. versionadded:: 2.4
"""
from .loaders import ModuleLoader
if log_function is None:
def log_function(x: str) -> None:
pass
assert log_function is not None
assert self.loader is not None, "No loader configured."
def write_file(filename: str, data: str) -> None:
if zip:
info = ZipInfo(filename)
info.external_attr = 0o755 << 16
zip_file.writestr(info, data)
else:
with open(os.path.join(target, filename), "wb") as f:
f.write(data.encode("utf8"))
if zip is not None:
from zipfile import ZIP_DEFLATED
from zipfile import ZIP_STORED
from zipfile import ZipFile
from zipfile import ZipInfo
zip_file = ZipFile(
target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]
)
log_function(f"Compiling into Zip archive {target!r}")
else:
if not os.path.isdir(target):
os.makedirs(target)
log_function(f"Compiling into folder {target!r}")
try:
for name in self.list_templates(extensions, filter_func):
source, filename, _ = self.loader.get_source(self, name)
try:
code = self.compile(source, name, filename, True, True)
except TemplateSyntaxError as e:
if not ignore_errors:
raise
log_function(f'Could not compile "{name}": {e}')
continue
filename = ModuleLoader.get_module_filename(name)
write_file(filename, code)
log_function(f'Compiled "{name}" as {filename}')
finally:
if zip:
zip_file.close()
log_function("Finished compiling templates")
| (self, target: Union[str, os.PathLike[str]], extensions: Optional[Collection[str]] = None, filter_func: Optional[Callable[[str], bool]] = None, zip: Optional[str] = 'deflated', log_function: Optional[Callable[[str], NoneType]] = None, ignore_errors: bool = True) -> NoneType |
37,457 | jinja2.environment | extend | Add the items to the instance of the environment if they do not exist
yet. This is used by :ref:`extensions <writing-extensions>` to register
callbacks and configuration values without breaking inheritance.
| def extend(self, **attributes: t.Any) -> None:
"""Add the items to the instance of the environment if they do not exist
yet. This is used by :ref:`extensions <writing-extensions>` to register
callbacks and configuration values without breaking inheritance.
"""
for key, value in attributes.items():
if not hasattr(self, key):
setattr(self, key, value)
| (self, **attributes: Any) -> NoneType |
37,458 | jinja2.environment | from_string | Load a template from a source string without using
:attr:`loader`.
:param source: Jinja source to compile into a template.
:param globals: Extend the environment :attr:`globals` with
these extra variables available for all renders of this
template. If the template has already been loaded and
cached, its globals are updated with any new items.
:param template_class: Return an instance of this
:class:`Template` class.
| def from_string(
self,
source: t.Union[str, nodes.Template],
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
template_class: t.Optional[t.Type["Template"]] = None,
) -> "Template":
"""Load a template from a source string without using
:attr:`loader`.
:param source: Jinja source to compile into a template.
:param globals: Extend the environment :attr:`globals` with
these extra variables available for all renders of this
template. If the template has already been loaded and
cached, its globals are updated with any new items.
:param template_class: Return an instance of this
:class:`Template` class.
"""
gs = self.make_globals(globals)
cls = template_class or self.template_class
return cls.from_code(self, self.compile(source), gs, None)
| (self, source: Union[str, jinja2.nodes.Template], globals: Optional[MutableMapping[str, Any]] = None, template_class: Optional[Type[jinja2.environment.Template]] = None) -> jinja2.environment.Template |
37,459 | jinja2.environment | get_or_select_template | Use :meth:`select_template` if an iterable of template names
is given, or :meth:`get_template` if one name is given.
.. versionadded:: 2.3
| @internalcode
def get_or_select_template(
self,
template_name_or_list: t.Union[
str, "Template", t.List[t.Union[str, "Template"]]
],
parent: t.Optional[str] = None,
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
) -> "Template":
"""Use :meth:`select_template` if an iterable of template names
is given, or :meth:`get_template` if one name is given.
.. versionadded:: 2.3
"""
if isinstance(template_name_or_list, (str, Undefined)):
return self.get_template(template_name_or_list, parent, globals)
elif isinstance(template_name_or_list, Template):
return template_name_or_list
return self.select_template(template_name_or_list, parent, globals)
| (self, template_name_or_list: Union[str, jinja2.environment.Template, List[Union[str, jinja2.environment.Template]]], parent: Optional[str] = None, globals: Optional[MutableMapping[str, Any]] = None) -> jinja2.environment.Template |
37,460 | jinja2.environment | get_template | Load a template by name with :attr:`loader` and return a
:class:`Template`. If the template does not exist a
:exc:`TemplateNotFound` exception is raised.
:param name: Name of the template to load. When loading
templates from the filesystem, "/" is used as the path
separator, even on Windows.
:param parent: The name of the parent template importing this
template. :meth:`join_path` can be used to implement name
transformations with this.
:param globals: Extend the environment :attr:`globals` with
these extra variables available for all renders of this
template. If the template has already been loaded and
cached, its globals are updated with any new items.
.. versionchanged:: 3.0
If a template is loaded from cache, ``globals`` will update
the template's globals instead of ignoring the new values.
.. versionchanged:: 2.4
If ``name`` is a :class:`Template` object it is returned
unchanged.
| @internalcode
def get_template(
self,
name: t.Union[str, "Template"],
parent: t.Optional[str] = None,
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
) -> "Template":
"""Load a template by name with :attr:`loader` and return a
:class:`Template`. If the template does not exist a
:exc:`TemplateNotFound` exception is raised.
:param name: Name of the template to load. When loading
templates from the filesystem, "/" is used as the path
separator, even on Windows.
:param parent: The name of the parent template importing this
template. :meth:`join_path` can be used to implement name
transformations with this.
:param globals: Extend the environment :attr:`globals` with
these extra variables available for all renders of this
template. If the template has already been loaded and
cached, its globals are updated with any new items.
.. versionchanged:: 3.0
If a template is loaded from cache, ``globals`` will update
the template's globals instead of ignoring the new values.
.. versionchanged:: 2.4
If ``name`` is a :class:`Template` object it is returned
unchanged.
"""
if isinstance(name, Template):
return name
if parent is not None:
name = self.join_path(name, parent)
return self._load_template(name, globals)
| (self, name: Union[str, jinja2.environment.Template], parent: Optional[str] = None, globals: Optional[MutableMapping[str, Any]] = None) -> jinja2.environment.Template |
37,461 | jinja2.environment | getattr | Get an item or attribute of an object but prefer the attribute.
Unlike :meth:`getitem` the attribute *must* be a string.
| def getattr(self, obj: t.Any, attribute: str) -> t.Any:
"""Get an item or attribute of an object but prefer the attribute.
Unlike :meth:`getitem` the attribute *must* be a string.
"""
try:
return getattr(obj, attribute)
except AttributeError:
pass
try:
return obj[attribute]
except (TypeError, LookupError, AttributeError):
return self.undefined(obj=obj, name=attribute)
| (self, obj: Any, attribute: str) -> Any |
37,462 | jinja2.environment | getitem | Get an item or attribute of an object but prefer the item. | def getitem(
self, obj: t.Any, argument: t.Union[str, t.Any]
) -> t.Union[t.Any, Undefined]:
"""Get an item or attribute of an object but prefer the item."""
try:
return obj[argument]
except (AttributeError, TypeError, LookupError):
if isinstance(argument, str):
try:
attr = str(argument)
except Exception:
pass
else:
try:
return getattr(obj, attr)
except AttributeError:
pass
return self.undefined(obj=obj, name=argument)
| (self, obj: Any, argument: Union[str, Any]) -> Union[Any, jinja2.runtime.Undefined] |
37,463 | jinja2.environment | handle_exception | Exception handling helper. This is used internally to either raise
rewritten exceptions or return a rendered traceback for the template.
| def handle_exception(self, source: t.Optional[str] = None) -> "te.NoReturn":
"""Exception handling helper. This is used internally to either raise
rewritten exceptions or return a rendered traceback for the template.
"""
from .debug import rewrite_traceback_stack
raise rewrite_traceback_stack(source=source)
| (self, source: Optional[str] = None) -> 'te.NoReturn' |
37,464 | jinja2.environment | iter_extensions | Iterates over the extensions by priority. | def iter_extensions(self) -> t.Iterator["Extension"]:
"""Iterates over the extensions by priority."""
return iter(sorted(self.extensions.values(), key=lambda x: x.priority))
| (self) -> Iterator[ForwardRef('Extension')] |
37,465 | jinja2.environment | join_path | Join a template with the parent. By default all the lookups are
relative to the loader root so this method returns the `template`
parameter unchanged, but if the paths should be relative to the
parent template, this function can be used to calculate the real
template name.
Subclasses may override this method and implement template path
joining here.
| def join_path(self, template: str, parent: str) -> str:
"""Join a template with the parent. By default all the lookups are
relative to the loader root so this method returns the `template`
parameter unchanged, but if the paths should be relative to the
parent template, this function can be used to calculate the real
template name.
Subclasses may override this method and implement template path
joining here.
"""
return template
| (self, template: str, parent: str) -> str |
37,466 | jinja2.environment | lex | Lex the given sourcecode and return a generator that yields
tokens as tuples in the form ``(lineno, token_type, value)``.
This can be useful for :ref:`extension development <writing-extensions>`
and debugging templates.
This does not perform preprocessing. If you want the preprocessing
of the extensions to be applied you have to filter source through
the :meth:`preprocess` method.
| def lex(
self,
source: str,
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
) -> t.Iterator[t.Tuple[int, str, str]]:
"""Lex the given sourcecode and return a generator that yields
tokens as tuples in the form ``(lineno, token_type, value)``.
This can be useful for :ref:`extension development <writing-extensions>`
and debugging templates.
This does not perform preprocessing. If you want the preprocessing
of the extensions to be applied you have to filter source through
the :meth:`preprocess` method.
"""
source = str(source)
try:
return self.lexer.tokeniter(source, name, filename)
except TemplateSyntaxError:
self.handle_exception(source=source)
| (self, source: str, name: Optional[str] = None, filename: Optional[str] = None) -> Iterator[Tuple[int, str, str]] |
37,467 | jinja2.environment | list_templates | Returns a list of templates for this environment. This requires
that the loader supports the loader's
:meth:`~BaseLoader.list_templates` method.
If there are other files in the template folder besides the
actual templates, the returned list can be filtered. There are two
ways: either `extensions` is set to a list of file extensions for
templates, or a `filter_func` can be provided which is a callable that
is passed a template name and should return `True` if it should end up
in the result list.
If the loader does not support that, a :exc:`TypeError` is raised.
.. versionadded:: 2.4
| def list_templates(
self,
extensions: t.Optional[t.Collection[str]] = None,
filter_func: t.Optional[t.Callable[[str], bool]] = None,
) -> t.List[str]:
"""Returns a list of templates for this environment. This requires
that the loader supports the loader's
:meth:`~BaseLoader.list_templates` method.
If there are other files in the template folder besides the
actual templates, the returned list can be filtered. There are two
ways: either `extensions` is set to a list of file extensions for
templates, or a `filter_func` can be provided which is a callable that
is passed a template name and should return `True` if it should end up
in the result list.
If the loader does not support that, a :exc:`TypeError` is raised.
.. versionadded:: 2.4
"""
assert self.loader is not None, "No loader configured."
names = self.loader.list_templates()
if extensions is not None:
if filter_func is not None:
raise TypeError(
"either extensions or filter_func can be passed, but not both"
)
def filter_func(x: str) -> bool:
return "." in x and x.rsplit(".", 1)[1] in extensions
if filter_func is not None:
names = [name for name in names if filter_func(name)]
return names
| (self, extensions: Optional[Collection[str]] = None, filter_func: Optional[Callable[[str], bool]] = None) -> List[str] |
37,468 | jinja2.environment | make_globals | Make the globals map for a template. Any given template
globals overlay the environment :attr:`globals`.
Returns a :class:`collections.ChainMap`. This allows any changes
to a template's globals to only affect that template, while
changes to the environment's globals are still reflected.
However, avoid modifying any globals after a template is loaded.
:param d: Dict of template-specific globals.
.. versionchanged:: 3.0
Use :class:`collections.ChainMap` to always prevent mutating
environment globals.
| def make_globals(
self, d: t.Optional[t.MutableMapping[str, t.Any]]
) -> t.MutableMapping[str, t.Any]:
"""Make the globals map for a template. Any given template
globals overlay the environment :attr:`globals`.
Returns a :class:`collections.ChainMap`. This allows any changes
to a template's globals to only affect that template, while
changes to the environment's globals are still reflected.
However, avoid modifying any globals after a template is loaded.
:param d: Dict of template-specific globals.
.. versionchanged:: 3.0
Use :class:`collections.ChainMap` to always prevent mutating
environment globals.
"""
if d is None:
d = {}
return ChainMap(d, self.globals)
| (self, d: Optional[MutableMapping[str, Any]]) -> MutableMapping[str, Any] |
37,469 | jinja2.environment | overlay | Create a new overlay environment that shares all the data with the
current environment except for cache and the overridden attributes.
Extensions cannot be removed for an overlayed environment. An overlayed
environment automatically gets all the extensions of the environment it
is linked to plus optional extra extensions.
Creating overlays should happen after the initial environment was set
up completely. Not all attributes are truly linked, some are just
copied over so modifications on the original environment may not shine
through.
.. versionchanged:: 3.1.2
Added the ``newline_sequence``,, ``keep_trailing_newline``,
and ``enable_async`` parameters to match ``__init__``.
| def overlay(
self,
block_start_string: str = missing,
block_end_string: str = missing,
variable_start_string: str = missing,
variable_end_string: str = missing,
comment_start_string: str = missing,
comment_end_string: str = missing,
line_statement_prefix: t.Optional[str] = missing,
line_comment_prefix: t.Optional[str] = missing,
trim_blocks: bool = missing,
lstrip_blocks: bool = missing,
newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = missing,
keep_trailing_newline: bool = missing,
extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = missing,
optimized: bool = missing,
undefined: t.Type[Undefined] = missing,
finalize: t.Optional[t.Callable[..., t.Any]] = missing,
autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = missing,
loader: t.Optional["BaseLoader"] = missing,
cache_size: int = missing,
auto_reload: bool = missing,
bytecode_cache: t.Optional["BytecodeCache"] = missing,
enable_async: bool = False,
) -> "Environment":
"""Create a new overlay environment that shares all the data with the
current environment except for cache and the overridden attributes.
Extensions cannot be removed for an overlayed environment. An overlayed
environment automatically gets all the extensions of the environment it
is linked to plus optional extra extensions.
Creating overlays should happen after the initial environment was set
up completely. Not all attributes are truly linked, some are just
copied over so modifications on the original environment may not shine
through.
.. versionchanged:: 3.1.2
Added the ``newline_sequence``,, ``keep_trailing_newline``,
and ``enable_async`` parameters to match ``__init__``.
"""
args = dict(locals())
del args["self"], args["cache_size"], args["extensions"], args["enable_async"]
rv = object.__new__(self.__class__)
rv.__dict__.update(self.__dict__)
rv.overlayed = True
rv.linked_to = self
for key, value in args.items():
if value is not missing:
setattr(rv, key, value)
if cache_size is not missing:
rv.cache = create_cache(cache_size)
else:
rv.cache = copy_cache(self.cache)
rv.extensions = {}
for key, value in self.extensions.items():
rv.extensions[key] = value.bind(rv)
if extensions is not missing:
rv.extensions.update(load_extensions(rv, extensions))
if enable_async is not missing:
rv.is_async = enable_async
return _environment_config_check(rv)
| (self, block_start_string: str = missing, block_end_string: str = missing, variable_start_string: str = missing, variable_end_string: str = missing, comment_start_string: str = missing, comment_end_string: str = missing, line_statement_prefix: Optional[str] = missing, line_comment_prefix: Optional[str] = missing, trim_blocks: bool = missing, lstrip_blocks: bool = missing, newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = missing, keep_trailing_newline: bool = missing, extensions: Sequence[Union[str, Type[ForwardRef('Extension')]]] = missing, optimized: bool = missing, undefined: Type[jinja2.runtime.Undefined] = missing, finalize: Optional[Callable[..., Any]] = missing, autoescape: Union[bool, Callable[[Optional[str]], bool]] = missing, loader: Optional[ForwardRef('BaseLoader')] = missing, cache_size: int = missing, auto_reload: bool = missing, bytecode_cache: Optional[ForwardRef('BytecodeCache')] = missing, enable_async: bool = False) -> 'Environment' |
37,470 | jinja2.environment | parse | Parse the sourcecode and return the abstract syntax tree. This
tree of nodes is used by the compiler to convert the template into
executable source- or bytecode. This is useful for debugging or to
extract information from templates.
If you are :ref:`developing Jinja extensions <writing-extensions>`
this gives you a good overview of the node tree generated.
| @internalcode
def parse(
self,
source: str,
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
) -> nodes.Template:
"""Parse the sourcecode and return the abstract syntax tree. This
tree of nodes is used by the compiler to convert the template into
executable source- or bytecode. This is useful for debugging or to
extract information from templates.
If you are :ref:`developing Jinja extensions <writing-extensions>`
this gives you a good overview of the node tree generated.
"""
try:
return self._parse(source, name, filename)
except TemplateSyntaxError:
self.handle_exception(source=source)
| (self, source: str, name: Optional[str] = None, filename: Optional[str] = None) -> jinja2.nodes.Template |
37,471 | jinja2.environment | preprocess | Preprocesses the source with all extensions. This is automatically
called for all parsing and compiling methods but *not* for :meth:`lex`
because there you usually only want the actual source tokenized.
| def preprocess(
self,
source: str,
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
) -> str:
"""Preprocesses the source with all extensions. This is automatically
called for all parsing and compiling methods but *not* for :meth:`lex`
because there you usually only want the actual source tokenized.
"""
return reduce(
lambda s, e: e.preprocess(s, name, filename),
self.iter_extensions(),
str(source),
)
| (self, source: str, name: Optional[str] = None, filename: Optional[str] = None) -> str |
37,472 | jinja2.environment | select_template | Like :meth:`get_template`, but tries loading multiple names.
If none of the names can be loaded a :exc:`TemplatesNotFound`
exception is raised.
:param names: List of template names to try loading in order.
:param parent: The name of the parent template importing this
template. :meth:`join_path` can be used to implement name
transformations with this.
:param globals: Extend the environment :attr:`globals` with
these extra variables available for all renders of this
template. If the template has already been loaded and
cached, its globals are updated with any new items.
.. versionchanged:: 3.0
If a template is loaded from cache, ``globals`` will update
the template's globals instead of ignoring the new values.
.. versionchanged:: 2.11
If ``names`` is :class:`Undefined`, an :exc:`UndefinedError`
is raised instead. If no templates were found and ``names``
contains :class:`Undefined`, the message is more helpful.
.. versionchanged:: 2.4
If ``names`` contains a :class:`Template` object it is
returned unchanged.
.. versionadded:: 2.3
| @internalcode
def select_template(
self,
names: t.Iterable[t.Union[str, "Template"]],
parent: t.Optional[str] = None,
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
) -> "Template":
"""Like :meth:`get_template`, but tries loading multiple names.
If none of the names can be loaded a :exc:`TemplatesNotFound`
exception is raised.
:param names: List of template names to try loading in order.
:param parent: The name of the parent template importing this
template. :meth:`join_path` can be used to implement name
transformations with this.
:param globals: Extend the environment :attr:`globals` with
these extra variables available for all renders of this
template. If the template has already been loaded and
cached, its globals are updated with any new items.
.. versionchanged:: 3.0
If a template is loaded from cache, ``globals`` will update
the template's globals instead of ignoring the new values.
.. versionchanged:: 2.11
If ``names`` is :class:`Undefined`, an :exc:`UndefinedError`
is raised instead. If no templates were found and ``names``
contains :class:`Undefined`, the message is more helpful.
.. versionchanged:: 2.4
If ``names`` contains a :class:`Template` object it is
returned unchanged.
.. versionadded:: 2.3
"""
if isinstance(names, Undefined):
names._fail_with_undefined_error()
if not names:
raise TemplatesNotFound(
message="Tried to select from an empty list of templates."
)
for name in names:
if isinstance(name, Template):
return name
if parent is not None:
name = self.join_path(name, parent)
try:
return self._load_template(name, globals)
except (TemplateNotFound, UndefinedError):
pass
raise TemplatesNotFound(names) # type: ignore
| (self, names: Iterable[Union[str, jinja2.environment.Template]], parent: Optional[str] = None, globals: Optional[MutableMapping[str, Any]] = None) -> jinja2.environment.Template |
37,473 | jinja2.loaders | PackageLoader | Load templates from a directory in a Python package.
:param package_name: Import name of the package that contains the
template directory.
:param package_path: Directory within the imported package that
contains the templates.
:param encoding: Encoding of template files.
The following example looks up templates in the ``pages`` directory
within the ``project.ui`` package.
.. code-block:: python
loader = PackageLoader("project.ui", "pages")
Only packages installed as directories (standard pip behavior) or
zip/egg files (less common) are supported. The Python API for
introspecting data in packages is too limited to support other
installation methods the way this loader requires.
There is limited support for :pep:`420` namespace packages. The
template directory is assumed to only be in one namespace
contributor. Zip files contributing to a namespace are not
supported.
.. versionchanged:: 3.0
No longer uses ``setuptools`` as a dependency.
.. versionchanged:: 3.0
Limited PEP 420 namespace package support.
| class PackageLoader(BaseLoader):
"""Load templates from a directory in a Python package.
:param package_name: Import name of the package that contains the
template directory.
:param package_path: Directory within the imported package that
contains the templates.
:param encoding: Encoding of template files.
The following example looks up templates in the ``pages`` directory
within the ``project.ui`` package.
.. code-block:: python
loader = PackageLoader("project.ui", "pages")
Only packages installed as directories (standard pip behavior) or
zip/egg files (less common) are supported. The Python API for
introspecting data in packages is too limited to support other
installation methods the way this loader requires.
There is limited support for :pep:`420` namespace packages. The
template directory is assumed to only be in one namespace
contributor. Zip files contributing to a namespace are not
supported.
.. versionchanged:: 3.0
No longer uses ``setuptools`` as a dependency.
.. versionchanged:: 3.0
Limited PEP 420 namespace package support.
"""
def __init__(
self,
package_name: str,
package_path: "str" = "templates",
encoding: str = "utf-8",
) -> None:
package_path = os.path.normpath(package_path).rstrip(os.path.sep)
# normpath preserves ".", which isn't valid in zip paths.
if package_path == os.path.curdir:
package_path = ""
elif package_path[:2] == os.path.curdir + os.path.sep:
package_path = package_path[2:]
self.package_path = package_path
self.package_name = package_name
self.encoding = encoding
# Make sure the package exists. This also makes namespace
# packages work, otherwise get_loader returns None.
import_module(package_name)
spec = importlib.util.find_spec(package_name)
assert spec is not None, "An import spec was not found for the package."
loader = spec.loader
assert loader is not None, "A loader was not found for the package."
self._loader = loader
self._archive = None
template_root = None
if isinstance(loader, zipimport.zipimporter):
self._archive = loader.archive
pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore
template_root = os.path.join(pkgdir, package_path).rstrip(os.path.sep)
else:
roots: t.List[str] = []
# One element for regular packages, multiple for namespace
# packages, or None for single module file.
if spec.submodule_search_locations:
roots.extend(spec.submodule_search_locations)
# A single module file, use the parent directory instead.
elif spec.origin is not None:
roots.append(os.path.dirname(spec.origin))
for root in roots:
root = os.path.join(root, package_path)
if os.path.isdir(root):
template_root = root
break
if template_root is None:
raise ValueError(
f"The {package_name!r} package was not installed in a"
" way that PackageLoader understands."
)
self._template_root = template_root
def get_source(
self, environment: "Environment", template: str
) -> t.Tuple[str, str, t.Optional[t.Callable[[], bool]]]:
# Use posixpath even on Windows to avoid "drive:" or UNC
# segments breaking out of the search directory. Use normpath to
# convert Windows altsep to sep.
p = os.path.normpath(
posixpath.join(self._template_root, *split_template_path(template))
)
up_to_date: t.Optional[t.Callable[[], bool]]
if self._archive is None:
# Package is a directory.
if not os.path.isfile(p):
raise TemplateNotFound(template)
with open(p, "rb") as f:
source = f.read()
mtime = os.path.getmtime(p)
def up_to_date() -> bool:
return os.path.isfile(p) and os.path.getmtime(p) == mtime
else:
# Package is a zip file.
try:
source = self._loader.get_data(p) # type: ignore
except OSError as e:
raise TemplateNotFound(template) from e
# Could use the zip's mtime for all template mtimes, but
# would need to safely reload the module if it's out of
# date, so just report it as always current.
up_to_date = None
return source.decode(self.encoding), p, up_to_date
def list_templates(self) -> t.List[str]:
results: t.List[str] = []
if self._archive is None:
# Package is a directory.
offset = len(self._template_root)
for dirpath, _, filenames in os.walk(self._template_root):
dirpath = dirpath[offset:].lstrip(os.path.sep)
results.extend(
os.path.join(dirpath, name).replace(os.path.sep, "/")
for name in filenames
)
else:
if not hasattr(self._loader, "_files"):
raise TypeError(
"This zip import does not have the required"
" metadata to list templates."
)
# Package is a zip file.
prefix = (
self._template_root[len(self._archive) :].lstrip(os.path.sep)
+ os.path.sep
)
offset = len(prefix)
for name in self._loader._files.keys():
# Find names under the templates directory that aren't directories.
if name.startswith(prefix) and name[-1] != os.path.sep:
results.append(name[offset:].replace(os.path.sep, "/"))
results.sort()
return results
| (package_name: str, package_path: 'str' = 'templates', encoding: str = 'utf-8') -> None |
37,474 | jinja2.loaders | __init__ | null | def __init__(
self,
package_name: str,
package_path: "str" = "templates",
encoding: str = "utf-8",
) -> None:
package_path = os.path.normpath(package_path).rstrip(os.path.sep)
# normpath preserves ".", which isn't valid in zip paths.
if package_path == os.path.curdir:
package_path = ""
elif package_path[:2] == os.path.curdir + os.path.sep:
package_path = package_path[2:]
self.package_path = package_path
self.package_name = package_name
self.encoding = encoding
# Make sure the package exists. This also makes namespace
# packages work, otherwise get_loader returns None.
import_module(package_name)
spec = importlib.util.find_spec(package_name)
assert spec is not None, "An import spec was not found for the package."
loader = spec.loader
assert loader is not None, "A loader was not found for the package."
self._loader = loader
self._archive = None
template_root = None
if isinstance(loader, zipimport.zipimporter):
self._archive = loader.archive
pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore
template_root = os.path.join(pkgdir, package_path).rstrip(os.path.sep)
else:
roots: t.List[str] = []
# One element for regular packages, multiple for namespace
# packages, or None for single module file.
if spec.submodule_search_locations:
roots.extend(spec.submodule_search_locations)
# A single module file, use the parent directory instead.
elif spec.origin is not None:
roots.append(os.path.dirname(spec.origin))
for root in roots:
root = os.path.join(root, package_path)
if os.path.isdir(root):
template_root = root
break
if template_root is None:
raise ValueError(
f"The {package_name!r} package was not installed in a"
" way that PackageLoader understands."
)
self._template_root = template_root
| (self, package_name: str, package_path: str = 'templates', encoding: str = 'utf-8') -> NoneType |
37,475 | jinja2.loaders | get_source | null | def get_source(
self, environment: "Environment", template: str
) -> t.Tuple[str, str, t.Optional[t.Callable[[], bool]]]:
# Use posixpath even on Windows to avoid "drive:" or UNC
# segments breaking out of the search directory. Use normpath to
# convert Windows altsep to sep.
p = os.path.normpath(
posixpath.join(self._template_root, *split_template_path(template))
)
up_to_date: t.Optional[t.Callable[[], bool]]
if self._archive is None:
# Package is a directory.
if not os.path.isfile(p):
raise TemplateNotFound(template)
with open(p, "rb") as f:
source = f.read()
mtime = os.path.getmtime(p)
def up_to_date() -> bool:
return os.path.isfile(p) and os.path.getmtime(p) == mtime
else:
# Package is a zip file.
try:
source = self._loader.get_data(p) # type: ignore
except OSError as e:
raise TemplateNotFound(template) from e
# Could use the zip's mtime for all template mtimes, but
# would need to safely reload the module if it's out of
# date, so just report it as always current.
up_to_date = None
return source.decode(self.encoding), p, up_to_date
| (self, environment: 'Environment', template: str) -> Tuple[str, str, Optional[Callable[[], bool]]] |
37,476 | jinja2.loaders | list_templates | null | def list_templates(self) -> t.List[str]:
results: t.List[str] = []
if self._archive is None:
# Package is a directory.
offset = len(self._template_root)
for dirpath, _, filenames in os.walk(self._template_root):
dirpath = dirpath[offset:].lstrip(os.path.sep)
results.extend(
os.path.join(dirpath, name).replace(os.path.sep, "/")
for name in filenames
)
else:
if not hasattr(self._loader, "_files"):
raise TypeError(
"This zip import does not have the required"
" metadata to list templates."
)
# Package is a zip file.
prefix = (
self._template_root[len(self._archive) :].lstrip(os.path.sep)
+ os.path.sep
)
offset = len(prefix)
for name in self._loader._files.keys():
# Find names under the templates directory that aren't directories.
if name.startswith(prefix) and name[-1] != os.path.sep:
results.append(name[offset:].replace(os.path.sep, "/"))
results.sort()
return results
| (self) -> List[str] |
37,477 | jinja2.loaders | load | Loads a template. This method looks up the template in the cache
or loads one by calling :meth:`get_source`. Subclasses should not
override this method as loaders working on collections of other
loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)
will not call this method but `get_source` directly.
| @internalcode
def load(
self,
environment: "Environment",
name: str,
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
) -> "Template":
"""Loads a template. This method looks up the template in the cache
or loads one by calling :meth:`get_source`. Subclasses should not
override this method as loaders working on collections of other
loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)
will not call this method but `get_source` directly.
"""
code = None
if globals is None:
globals = {}
# first we try to get the source for this template together
# with the filename and the uptodate function.
source, filename, uptodate = self.get_source(environment, name)
# try to load the code from the bytecode cache if there is a
# bytecode cache configured.
bcc = environment.bytecode_cache
if bcc is not None:
bucket = bcc.get_bucket(environment, name, filename, source)
code = bucket.code
# if we don't have code so far (not cached, no longer up to
# date) etc. we compile the template
if code is None:
code = environment.compile(source, name, filename)
# if the bytecode cache is available and the bucket doesn't
# have a code so far, we give the bucket the new code and put
# it back to the bytecode cache.
if bcc is not None and bucket.code is None:
bucket.code = code
bcc.set_bucket(bucket)
return environment.template_class.from_code(
environment, code, globals, uptodate
)
| (self, environment: 'Environment', name: str, globals: Optional[MutableMapping[str, Any]] = None) -> 'Template' |
37,478 | flask_debugtoolbar | _printable | null | def _printable(value):
try:
return decode_text(repr(value))
except Exception as e:
return '<repr(%s) raised %s: %s>' % (
object.__repr__(value), type(e).__name__, e)
| (value) |
37,481 | flask_debugtoolbar.utils | decode_text |
Decode a text-like value for display.
Unicode values are returned unchanged. Byte strings will be decoded
with a text-safe replacement for unrecognized characters.
| def decode_text(value):
"""
Decode a text-like value for display.
Unicode values are returned unchanged. Byte strings will be decoded
with a text-safe replacement for unrecognized characters.
"""
if isinstance(value, bytes):
return value.decode('ascii', 'replace')
else:
return value
| (value) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.