repo_name stringlengths 7 65 | path stringlengths 5 185 | copies stringlengths 1 4 | size stringlengths 4 6 | content stringlengths 977 990k | license stringclasses 14 values | hash stringlengths 32 32 | line_mean float64 7.18 99.4 | line_max int64 31 999 | alpha_frac float64 0.25 0.95 | ratio float64 1.5 7.84 | autogenerated bool 1 class | config_or_test bool 2 classes | has_no_keywords bool 2 classes | has_few_assignments bool 1 class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
yashaka/selene | tests/integration/browser__open_test.py | 1 | 1590 | # MIT License
#
# Copyright (c) 2015-2022 Iakiv Kramarenko
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from selene import Browser, Config
from tests.integration.helpers import givenpage
def test_changes_window_size_on_open_according_to_config(chrome_driver):
browser = Browser(
Config(
driver=chrome_driver,
window_width=640,
window_height=480,
)
)
browser.open(givenpage.EMPTY_PAGE_URL)
assert browser.driver.get_window_size()['width'] == 640
assert browser.driver.get_window_size()['height'] == 480
| mit | f621aacfc37b3612d39dce066277d7d7 | 40.842105 | 80 | 0.741509 | 4.228723 | false | true | false | false |
yashaka/selene | tests/integration/element__scroll_to__test.py | 1 | 2338 | # MIT License
#
# Copyright (c) 2015-2022 Iakiv Kramarenko
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from selene import be, command
from tests.integration.helpers.givenpage import GivenPage
def test_can_scroll_to_element_manually(session_browser):
session_browser.driver.set_window_size(1000, 100)
GivenPage(session_browser.driver).opened_with_body(
'''
<div id="paragraph" style="margin: 400px">
</div>
<a id="not-viewable-link" href="#header"/>
<h1 id="header">Heading 1</h2>
'''
)
element = session_browser.element("#not-viewable-link")
element.perform(command.js.scroll_into_view)
element.click() # we can click even if we did not make the scrolling
# TODO: find the way to assert that scroll worked!
assert "header" in session_browser.driver.current_url
def test_can_scroll_to_element_automatically(session_browser):
session_browser.driver.set_window_size(1000, 100)
GivenPage(session_browser.driver).opened_with_body(
'''
<div id="paragraph" style="margin: 400px">
</div>
<a id="not-viewable-link" href="#header"/>
<h1 id="header">Heading 1</h2>
'''
)
session_browser.element("#not-viewable-link").click()
assert "header" in session_browser.driver.current_url
| mit | 6b6ff4da526c3133994fec37dbd303c7 | 39.310345 | 80 | 0.714713 | 3.922819 | false | true | false | false |
yashaka/selene | tests/examples/test_wait_until.py | 1 | 3132 | # MIT License
#
# Copyright (c) 2015-2022 Iakiv Kramarenko
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.core.utils import ChromeType
from selene import Browser, Config
from selene.support.conditions import be
@pytest.fixture(scope='function')
def browser():
browser = Browser(
Config(
driver=webdriver.Chrome(
service=Service(
ChromeDriverManager(
chrome_type=ChromeType.GOOGLE
).install()
)
)
)
)
yield browser
browser.quit()
def test_progress_bar_disappears_in_time(browser):
"""Test for page with progress bar that appears each time after click on a button.
Test should use wait_until for progress bar to disappear
if disappeared:
pass the test
else
fail the test
"""
show_dialog_btn = browser.element('.btn-primary')
dialog = browser.element('.modal-backdrop.fade.in')
browser.open(
'https://demo.seleniumeasy.com/bootstrap-progress-bar-dialog-demo.html'
)
show_dialog_btn.click()
dialog.should(be.visible)
disappeared = dialog.wait_until(be.not_.present)
assert disappeared is True
def test_progress_bar_does_not_disappear_in_time(browser):
"""Test for page with progress bar that appears each time after click on a button.
Test should use wait_until for progress bar to not disappear in timeout
if not disappeared:
pass the test
else
fail the test
"""
show_dialog_btn = browser.element('.btn-primary')
dialog = browser.element('.modal-backdrop.fade.in')
browser.open(
'https://demo.seleniumeasy.com/bootstrap-progress-bar-dialog-demo.html'
)
show_dialog_btn.click()
dialog.should(be.visible)
disappeared = dialog.with_(timeout=1).wait_until(be.not_.present)
assert disappeared is False
| mit | 046caff8c66aae324fcf38afcd77f6e7 | 33.8 | 86 | 0.698276 | 4.204027 | false | true | false | false |
uclapi/uclapi | backend/uclapi/dashboard/views.py | 1 | 3789 | import os
from distutils.util import strtobool
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.utils.http import quote
from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
from uclapi.settings import FAIR_USE_POLICY
from oauth.app_helpers import validate_shibboleth_callback
from .app_helpers import get_articles, get_temp_token
from .models import User
from .tasks import add_user_to_mailing_list_task
@csrf_exempt
def shibboleth_callback(request):
# should auth user login or signup
# then redirect to dashboard homepage
validation_result = validate_shibboleth_callback(request)
if isinstance(validation_result, str):
response = HttpResponse("Error 400 - Bad Request. <br>" + validation_result)
response.status_code = 400
return response
user = validation_result
groups = request.META.get('HTTP_UCLINTRANETGROUPS', '')
# Check whether the user is a member of any UCL Intranet Groups.
# This is a quick litmus test to determine whether they should have
# access to the dashboard.
# We deny access to test accounts and alumni, neither of which have
# this Shibboleth attribute.
if not groups:
response = HttpResponse(
(
"Error 403 - denied. <br>"
"The API Dashboard is only assessible to active UCL users."
)
)
response.status_code = 403
return response
request.session["user_id"] = user.id
add_user_to_mailing_list_task.delay(user.email, user.full_name)
return redirect(dashboard)
@ensure_csrf_cookie
def dashboard(request):
try:
user_id = request.session["user_id"]
except KeyError:
url = os.environ["SHIBBOLETH_ROOT"] + "/Login?target="
param = (request.build_absolute_uri(request.path)
+ "user/login.callback")
param = quote(param)
url = url + param
return redirect(url)
user = User.objects.get(id=user_id)
if not user.agreement:
if request.method != "POST":
return render(request, "agreement.html", {
'fair_use': FAIR_USE_POLICY
})
try:
agreement = strtobool(request.POST["agreement"])
except (KeyError, ValueError):
return render(request, "agreement.html", {
'fair_use': FAIR_USE_POLICY,
"error": "You must agree to the fair use policy"
})
if agreement:
user.agreement = True
user.save()
else:
return render(request, "agreement.html", {
'fair_use': FAIR_USE_POLICY,
"error": "You must agree to the fair use policy"
})
return render(request, 'dashboard.html')
@ensure_csrf_cookie
def about(request):
return render(request, 'about.html')
@ensure_csrf_cookie
def home(request):
logged_in = True
try:
request.session["user_id"]
except KeyError:
logged_in = False
articles = get_articles()
token = get_temp_token()
return render(request, 'index.html', {
'initial_data': {
'temp_token': token,
'logged_in': str(logged_in),
'medium_articles': articles
}
})
@ensure_csrf_cookie
def documentation(request):
return render(request, 'documentation.html')
@ensure_csrf_cookie
def warning(request):
return render(request, 'warning.html')
@ensure_csrf_cookie
def error_404_view(request, exception):
return render(request, '404.html', status=404)
def error_500_view(request):
return render(request, '500.html', status=500)
def custom_page_not_found(request):
return error_404_view(request, None)
| mit | 0a291af64e2be2f13e34d3d40ab43614 | 27.066667 | 84 | 0.634204 | 3.878199 | false | false | false | false |
yashaka/selene | tests/integration/browser__execute_script_test.py | 1 | 2373 | # MIT License
#
# Copyright (c) 2015-2022 Iakiv Kramarenko
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from tests.integration.helpers.givenpage import GivenPage
def test_can_scroll_to_via_js(function_browser):
function_browser.driver.set_window_size(300, 200)
GivenPage(function_browser.driver).opened_with_body(
'''
<div id="paragraph" style="margin: 400px">
</div>
<a id="not-viewable-link" href="#header"/>
<h1 id="header">Heading 1</h2>
'''
)
link = function_browser.element("#not-viewable-link")
# browser.driver().execute_script("arguments[0].scrollIntoView();", link)
# - this code does not work because SeleneElement is not JSON serializable, and I don't know the way to fix it
# - because all available in python options needs a change to json.dumps call - adding a second parameter to it
# and specify a custom encoder, but we can't change this call inside selenium webdriver implementation
function_browser.driver.execute_script(
"arguments[0].scrollIntoView();", link()
)
link.click()
# actually, selene .click() scrolls to any element in dom, so it's not an option fo
# in this case we should find another way to check page is scrolled down or to choose another script.
assert "header" in function_browser.driver.current_url
| mit | 00c3c64b25188b9b584f5dddec24a52d | 48.4375 | 117 | 0.729456 | 4.134146 | false | false | false | false |
yashaka/selene | selene/core/wait.py | 1 | 5505 | # MIT License
#
# Copyright (c) 2015-2022 Iakiv Kramarenko
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import time
import warnings
from abc import abstractmethod, ABC
from typing import Generic, Callable, TypeVar, Optional
from selene.common import fp
from selene.core.exceptions import TimeoutException
from selene.common.fp import identity
T = TypeVar('T')
R = TypeVar('R')
E = TypeVar('E')
'''
A generic TypeVar to identify an Entity Type, i.e. something to wait on
'''
# todo: not sure, if we need all these Lambda, Proc, Query, Command in python
# todo: they was added just to quickly port selenidejs waiting mechanism
# todo: let's consider removing them... or moving them e.g. to fp
Lambda = Callable[[T], R]
Proc = Callable[[T], None]
Predicate = Callable[[T], bool]
Fn = Callable[[T], R]
# todo: consider moving outside of "wait" module... because there is no direct cohesion with it
class Query(Generic[T, R]):
def __init__(self, description: str, fn: Callable[[T], R]):
self._description = description
self._fn = fn
def __call__(self, entity: T) -> R:
return self._fn(entity)
def __str__(self):
return self._description
class Command(Query[T, None]):
pass
# todo: provide sexy fluent implementation via builder, i.e. Wait.the(element).atMost(3).orFailWith(hook)
class Wait(Generic[E]):
# todo: provide the smallest possible timeout default, something like 1ms
def __init__(
self,
entity: E,
at_most: float,
or_fail_with: Optional[Callable[[TimeoutException], Exception]] = None,
_decorator: Callable[
[Wait[E]], Callable[[fp.T], fp.T]
] = lambda _: identity,
):
self.entity = entity
self._timeout = at_most
self._hook_failure = or_fail_with or identity
self._decorator = _decorator
@property
def _entity(self):
warnings.warn(
'wait.entity will be removed in next version, '
+ 'please use wait.entity instead',
DeprecationWarning,
)
return self.entity
def at_most(self, timeout: float) -> Wait[E]:
return Wait(self.entity, timeout, self._hook_failure)
def or_fail_with(
self, hook_failure: Optional[Callable[[TimeoutException], Exception]]
) -> Wait[E]:
return Wait(self.entity, self._timeout, hook_failure)
@property
def hook_failure(
self,
) -> Optional[Callable[[TimeoutException], Exception]]:
# todo: hook_failure or failure_hook?
return self._hook_failure
# todo: consider renaming to `def to(...)`, though will sound awkward when wait.to(condition)
def for_(self, fn: Callable[[E], R]) -> R:
@self._decorator(self)
def _(fn: Callable[[E], R]) -> R:
finish_time = time.time() + self._timeout
while True:
try:
return fn(self.entity)
except Exception as reason:
if time.time() > finish_time:
reason_message = str(reason)
reason_string = '{name}: {message}'.format(
name=reason.__class__.__name__,
message=reason_message,
)
# todo: think on how can we improve logging failures in selene, e.g. reverse msg and stacktrace
# stacktrace = getattr(reason, 'stacktrace', None)
timeout = self._timeout
entity = self.entity
failure = TimeoutException(
f'\n'
f'\nTimed out after {timeout}s, while waiting for:'
f'\n{entity}.{fn}'
f'\n'
f'\nReason: {reason_string}'
)
raise self._hook_failure(failure)
return _(fn)
def until(self, fn: Callable[[E], R]) -> bool:
try:
self.for_(fn)
return True
except TimeoutException:
return False
# todo: do we really need these aliases?
def command(self, description: str, fn: Callable[[E], None]) -> None:
self.for_(Command(description, fn))
def query(self, description: str, fn: Callable[[E], R]) -> R:
return self.for_(Query(description, fn))
| mit | 3b1fc582791c88742e097bdfe4b3955c | 33.192547 | 119 | 0.605086 | 4.257541 | false | false | false | false |
uclapi/uclapi | backend/uclapi/timetable/migrations/0010_auto_20190220_1835.py | 1 | 3406 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-02-20 18:35
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('timetable', '0009_coursea_courseb'),
]
operations = [
migrations.AlterField(
model_name='modulegroupsa',
name='csize',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='modulegroupsa',
name='estsize',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='modulegroupsa',
name='groupnum',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='modulegroupsa',
name='maxsize',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='modulegroupsa',
name='mequivid',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='modulegroupsa',
name='minsize',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='modulegroupsa',
name='parentkey',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='modulegroupsa',
name='prefmaxsize',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='modulegroupsa',
name='thiskey',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='modulegroupsb',
name='csize',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='modulegroupsb',
name='estsize',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='modulegroupsb',
name='groupnum',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='modulegroupsb',
name='maxsize',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='modulegroupsb',
name='mequivid',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='modulegroupsb',
name='minsize',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='modulegroupsb',
name='parentkey',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='modulegroupsb',
name='prefmaxsize',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='modulegroupsb',
name='thiskey',
field=models.IntegerField(blank=True, null=True),
),
]
| mit | aebdaf4372e17d0908822a1d29f16aab | 31.438095 | 61 | 0.551674 | 4.553476 | false | false | false | false |
yashaka/selene | tests/integration/collection__filtered_by_condition__lazy_search_test.py | 1 | 2844 | # MIT License
#
# Copyright (c) 2015-2022 Iakiv Kramarenko
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from selene import have
from tests.integration.helpers.givenpage import GivenPage
def test_search_is_lazy_and_does_not_start_on_creation(session_browser):
page = GivenPage(session_browser.driver)
page.opened_empty()
non_existent_collection = session_browser.all('.not-existing').by(
have.css_class('special')
)
assert str(non_existent_collection)
def test_search_is_postponed_until_actual_action_like_questioning_count(
session_browser,
):
page = GivenPage(session_browser.driver)
page.opened_empty()
elements = session_browser.all('li').by(have.css_class('will-appear'))
page.load_body(
'''
<ul>Hello to:
<li>Anonymous</li>
<li class='will-appear'>Bob</li>
<li class='will-appear'>Kate</li>
</ul>
'''
)
count = len(elements)
assert count == 2
def test_search_is_updated_on_next_actual_action_like_questioning_count(
session_browser,
):
page = GivenPage(session_browser.driver)
page.opened_empty()
elements = session_browser.all('li').by(have.css_class('will-appear'))
page.load_body(
'''
<ul>Hello to:
<li>Anonymous</li>
<li class='will-appear'>Bob</li>
<li class='will-appear'>Kate</li>
</ul>
'''
)
original_count = len(elements)
page.load_body(
'''
<ul>Hello to:
<li>Anonymous</li>
<li class='will-appear'>Bob</li>
<li class='will-appear'>Kate</li>
<li class='will-appear'>Joe</li>
</ul>
'''
)
updated_count = len(elements)
assert updated_count == 3
assert updated_count != original_count
| mit | c85230e472e0d9923abaf47638f12a28 | 31.318182 | 80 | 0.662096 | 3.822581 | false | false | false | false |
uclapi/uclapi | backend/uclapi/roombookings/helpers.py | 1 | 10126 | from __future__ import unicode_literals
import datetime
import json
from datetime import timedelta
import ciso8601
import pytz
import redis
from django.conf import settings
from django.core.exceptions import FieldError
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.db.models import Q
from .api_helpers import generate_token
from .models import BookingA, BookingB, Location, SiteLocation
from common.helpers import PrettyJsonResponse
from timetable.models import Lock
TOKEN_EXPIRY_TIME = 30 * 60
ROOM_TYPE_MAP = {
"AN": "Anechoic Chamber",
"CI": "Clinic Room",
"CF": "Catering Facilities",
"CFE": "Cafe",
"CL": "Cloakroom",
"CR": "Classroom",
"ER": "Equipment Room",
"IN": "Installation",
"LA": "Laboratory",
"LB": "Library",
"LT": "Lecture Theatre",
"MR": "Meeting Room",
"OF": "Office",
"PC1": "Public Cluster",
"PC2": "Public Cluster - Tutorial",
"PC3": "Public Cluster - Students",
"RC": "Reverberation Chamber",
"SS": "Social Space",
"STU": "Studio",
"TH": "Theatre",
}
def _create_page_token(query, pagination):
r = redis.Redis(host=settings.REDIS_UCLAPI_HOST)
page_data = {
"current_page": 0,
"pagination": pagination,
"query": json.dumps(query, default=str),
}
page_token = generate_token()
r.set(page_token, json.dumps(page_data), ex=TOKEN_EXPIRY_TIME)
return page_token
def _get_paginated_bookings(page_token):
r = redis.Redis(host=settings.REDIS_UCLAPI_HOST)
try:
page_data = json.loads(r.get(page_token).decode('ascii'))
except (AttributeError, json.decoder.JSONDecodeError):
return {
"error": "Page token does not exist"
}
page_data["current_page"] += 1
r.set(page_token, json.dumps(page_data), ex=TOKEN_EXPIRY_TIME)
pagination = page_data["pagination"]
query = json.loads(page_data["query"])
bookings, is_last_page = _paginated_result(
query,
page_data["current_page"],
pagination
)
# if there is a next page
bookings["next_page_exists"] = not is_last_page
if not is_last_page:
# append the page_token to return json
bookings["page_token"] = page_token
return bookings
def _paginated_result(query, page_number, pagination):
try:
lock = Lock.objects.all()[0]
curr = BookingA if lock.a else BookingB
all_bookings = curr.objects.filter(
Q(bookabletype='CB') | Q(siteid='238') | Q(siteid='240'),
**query
).order_by('startdatetime')
except FieldError:
return {
"error": "something wrong with encoded query params"
}, False
paginator = Paginator(all_bookings, pagination)
try:
bookings = paginator.page(page_number)
except PageNotAnInteger:
# give first page
bookings = paginator.page(1)
except EmptyPage:
# return empty page
# bookings = paginator.page(paginator.num_pages)
bookings = []
serialized_bookings = _serialize_bookings(bookings)
return (
{"bookings": serialized_bookings},
(page_number == paginator.num_pages)
)
def _localize_time(time_string):
london_time = pytz.timezone("Europe/London")
ret_time = time_string.replace(" ", "+")
ret_time = ciso8601.parse_datetime(ret_time)
ret_time = ret_time.astimezone(london_time)
return ret_time.replace(tzinfo=None)
def _round_date(time_string, up=False):
"""
Rounds the datetime to the nearest day.
Rounds down by default until up is passed as True in which case
it rounds up
"""
date = datetime.date(
time_string.year,
time_string.month,
time_string.day
)
if up:
date += datetime.timedelta(days=1)
return date
def _parse_datetime(start_time, end_time, search_date):
parsed_start_time, parsed_end_time = None, None
try:
if start_time:
# + gets decoded into a space in params
parsed_start_time = _localize_time(start_time)
if end_time:
parsed_end_time = _localize_time(end_time)
if not end_time and not start_time:
if search_date:
search_date = datetime.datetime.strptime(
search_date, "%Y%m%d").date()
parsed_start_time = datetime.datetime.combine(
search_date,
datetime.time.min # start of the day
)
parsed_end_time = datetime.datetime.combine(
search_date,
datetime.time.max # end of the day
)
except (TypeError, NameError, ValueError, AttributeError):
return -1, -1, False
return parsed_start_time, parsed_end_time, True
def _serialize_rooms(room_set):
rooms = []
for room in room_set:
# Maps room classification to a textual version
# e.g. LT => Lecture Theatre
classification_name = ROOM_TYPE_MAP.get(
room.roomclass,
"Unknown Room Type"
)
room_to_add = {
"roomname": room.roomname,
"roomid": room.roomid,
"siteid": room.siteid,
"sitename": room.sitename,
"capacity": room.capacity,
"classification": room.roomclass,
"classification_name": classification_name,
"automated": room.automated,
"location": {
"address": [
room.address1,
room.address2,
room.address3,
room.address4
]
}
}
try:
location = Location.objects.get(
siteid=room.siteid,
roomid=room.roomid
)
room_to_add['location']['coordinates'] = {
"lat": location.lat,
"lng": location.lng
}
except Location.DoesNotExist:
# no location for this room, try building
try:
location = SiteLocation.objects.get(
siteid=room.siteid
)
room_to_add['location']['coordinates'] = {
"lat": location.lat,
"lng": location.lng
}
except SiteLocation.DoesNotExist:
# no location for this room
pass
rooms.append(room_to_add)
return rooms
def _serialize_bookings(bookings):
ret_bookings = []
for bk in bookings:
ret_bookings.append({
"roomname": bk.roomname,
"siteid": bk.siteid,
"roomid": bk.roomid,
"description": bk.title,
"start_time": _kloppify(datetime.datetime.strftime(
bk.startdatetime, "%Y-%m-%dT%H:%M:%S"), bk.startdatetime),
"end_time": _kloppify(datetime.datetime.strftime(
bk.finishdatetime, "%Y-%m-%dT%H:%M:%S"), bk.finishdatetime),
"contact": bk.condisplayname,
"slotid": bk.slotid,
"weeknumber": bk.weeknumber,
"phone": bk.phone
})
return ret_bookings
def _serialize_equipment(equipment):
ret_equipment = []
for item in equipment:
ret_equipment.append({
"type": item.type,
"description": item.description,
"units": item.units
})
return ret_equipment
def _kloppify(date_string, date):
local_time = pytz.timezone('Europe/London')
if (local_time.localize(date).dst() > timedelta(0)):
return date_string + "+01:00"
return date_string + "+00:00"
def _return_json_bookings(bookings, custom_header_data=None):
if "error" in bookings:
return PrettyJsonResponse({
"ok": False,
"error": bookings["error"]
}, custom_header_data)
bookings["ok"] = True
return PrettyJsonResponse(bookings, custom_header_data)
def how_many_seconds_until_midnight():
"""Returns the number of seconds until midnight."""
tomorrow = datetime.datetime.now() + timedelta(days=1)
midnight = datetime.datetime(
year=tomorrow.year, month=tomorrow.month,
day=tomorrow.day, hour=0, minute=0, second=0
)
return (midnight - datetime.datetime.now()).seconds
def _create_map_of_overlapping_bookings(bookings, start, end):
"""
Creates map of room to bookings where each booking overlaps
with the given time range
"""
bookings_map = {}
for booking in bookings:
booking_start = _localize_time(booking["start_time"])
booking_end = _localize_time(booking["end_time"])
if _overlaps(
start1=booking_start,
end1=booking_end,
start2=start,
end2=end
):
roomid, siteid = booking["roomid"], booking["siteid"]
bookings_map[(roomid, siteid)] = bookings_map.get(
(roomid, siteid), []
) + [booking]
return bookings_map
def _overlaps(start1, end1, start2, end2):
"""
takes 4 datetimes
checks if they overlap
"""
return max(start1, start2) < min(end1, end2)
def _filter_for_free_rooms(all_rooms, bookings, start, end):
"""
Find all rooms which don't have any bookings.
Args:
all_rooms: All available rooms.
bookings: All the bookings made in the days of the given time period
start: Start time for free rooms
end: End time for free rooms
"""
rooms_with_bookings = list(all_rooms)
bookings_map = _create_map_of_overlapping_bookings(bookings, start, end)
free_rooms = []
for room in rooms_with_bookings:
roomid, siteid = room["roomid"], room["siteid"]
if (
(roomid, siteid) not in bookings_map or
not bookings_map[(roomid, siteid)]
):
# if room doesn't have any overlapping bookings
free_rooms.append(room)
return free_rooms
| mit | aef4137ce05591c48645798cf8bdd729 | 27.849003 | 76 | 0.576931 | 3.743438 | false | false | false | false |
uclapi/uclapi | backend/uclapi/uclapi/celery.py | 1 | 3967 | from __future__ import absolute_import, unicode_literals
import celery
import os
from common.helpers import read_dotenv
read_dotenv(os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'uclapi.settings')
class Celery(celery.Celery):
def on_configure(self):
if os.environ.get("SENTRY_DSN") is not None:
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
from sentry_sdk.integrations.celery import CeleryIntegration
sentry_sdk.init(dsn=os.environ.get("SENTRY_DSN"),
integrations=[DjangoIntegration(), CeleryIntegration()],
traces_sample_rate=0.01,
send_default_pii=True)
app = Celery('uclapi')
app.config_from_object('django.conf.settings', namespace='CELERY')
app.autodiscover_tasks()
@app.on_after_finalize.connect
def setup_periodic_tasks(sender, **kwargs):
from django_celery_beat.models import CrontabSchedule, PeriodicTask
# Gencache at every 5th and 35th minute
gencache_schedule, _ = CrontabSchedule.objects.get_or_create(minute='5,35', hour='*',
day_of_week='*', day_of_month='*',
month_of_year='*')
gencache_periodic_task = PeriodicTask.objects.filter(task='timetable.tasks.update_gencache_celery').first()
if gencache_periodic_task is None:
gencache_periodic_task = PeriodicTask(task='timetable.tasks.update_gencache_celery')
gencache_periodic_task.crontab = gencache_schedule
gencache_periodic_task.name = 'Update gencache'
gencache_periodic_task.save()
# Day cache for occupeye every 2 minutes
day_cache_schedule, _ = CrontabSchedule.objects.get_or_create(minute='*/2', hour='*',
day_of_week='*', day_of_month='*',
month_of_year='*')
occupeye_day_periodic_task = PeriodicTask.objects.filter(task='workspaces.tasks.day_cache').first()
if occupeye_day_periodic_task is None:
occupeye_day_periodic_task = PeriodicTask(task='workspaces.tasks.day_cache')
occupeye_day_periodic_task.crontab = day_cache_schedule
occupeye_day_periodic_task.name = 'Occupeye day cache'
occupeye_day_periodic_task.save()
# Night cache for occupeye at 2AM every day
night_cache_schedule, _ = CrontabSchedule.objects.get_or_create(minute='0', hour='2',
day_of_week='*', day_of_month='*',
month_of_year='*')
occupeye_night_periodic_task = PeriodicTask.objects.filter(task='workspaces.tasks.night_cache').first()
if occupeye_night_periodic_task is None:
occupeye_night_periodic_task = PeriodicTask(task='workspaces.tasks.night_cache')
occupeye_night_periodic_task.crontab = night_cache_schedule
occupeye_night_periodic_task.name = 'Occupeye night cache'
occupeye_night_periodic_task.save()
# Update LibCal token every 30 minutes
libcal_token_schedule, _ = CrontabSchedule.objects.get_or_create(minute='*/30', hour='*',
day_of_week='*', day_of_month='*',
month_of_year='*')
libcal_token_task = PeriodicTask.objects.filter(task='libcal.tasks.refresh_libcal_token').first()
if libcal_token_task is None:
libcal_token_task = PeriodicTask(task='libcal.tasks.refresh_libcal_token')
libcal_token_task.crontab = libcal_token_schedule
libcal_token_task.name = 'LibCal token refresh'
libcal_token_task.save()
@app.task()
def ping_sample_task():
return True
| mit | f174c73763315ed0c412916bac387d6a | 46.795181 | 111 | 0.605495 | 3.778095 | false | false | false | false |
appleseedhq/blenderseed | operators/osl_ops.py | 2 | 5298 | #
# This source file is part of appleseed.
# Visit https://appleseedhq.net/ for additional information and resources.
#
# This software is released under the MIT license.
#
# Copyright (c) 2019 Jonathan Dent, The appleseedhq Organization
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import bpy
import appleseed as asr
from ..properties.nodes import AppleseedOSLScriptNode
from ..utils import path_util, osl_utils, util
class ASMAT_OT_compile_script(bpy.types.Operator):
bl_idname = "appleseed.compile_osl_script"
bl_label = "Compile OSL Script Node Parameters"
def execute(self, context):
temp_values = dict()
input_connections = dict()
output_connections = dict()
material = context.object.active_material
node_tree = material.node_tree
node = node_tree.nodes.active
location = node.location
width = node.width
script = node.script
if node.script is not None:
# Save existing connections and parameters
for key, value in node.items():
temp_values[key] = value
for input_iter in node.inputs:
if input_iter.is_linked:
input_connections[input_iter.bl_idname] = input_iter.links[0].from_socket
for output in node.outputs:
if output.is_linked:
outputs = []
for link in output.links:
outputs.append(link.to_socket)
output_connections[output.bl_idname] = outputs
stdosl_path = path_util.get_stdosl_paths()
compiler = asr.ShaderCompiler(stdosl_path)
osl_bytecode = osl_utils.compile_osl_bytecode(compiler,
script)
if osl_bytecode is not None:
q = asr.ShaderQuery()
q.open_bytecode(osl_bytecode)
node_data = osl_utils.parse_shader(q)
node_name, node_category, node_classes = osl_utils.generate_node(node_data,
AppleseedOSLScriptNode)
for cls in reversed(node.classes):
util.safe_unregister_class(cls)
for cls in node_classes:
util.safe_register_class(cls)
node_tree.nodes.remove(node)
new_node = node_tree.nodes.new(node_name)
new_node.location = location
new_node.width = width
new_node.classes.extend(node_classes)
setattr(new_node, "node_type", "osl_script")
# Copy variables to new node
for variable, value in temp_values.items():
if variable in dir(new_node):
setattr(new_node, variable, value)
# Recreate node connections
for connection, sockets in output_connections.items():
for output in new_node.outputs:
if output.bl_idname == connection:
output_socket_class = output
if output_socket_class:
for output_connection in sockets:
node_tree.links.new(output_socket_class,
output_connection)
for connection, sockets in input_connections.items():
for in_socket in new_node.inputs:
if in_socket.bl_idname == connection:
input_socket_class = in_socket
if input_socket_class:
for input_connection in sockets:
node_tree.links.new(input_socket_class,
input_connection)
else:
self.report(
{'ERROR'}, "appleseed - OSL script did not compile!")
else:
self.report({'ERROR'}, "appleseed - No OSL script selected!")
return {'FINISHED'}
def register():
util.safe_register_class(ASMAT_OT_compile_script)
def unregister():
util.safe_unregister_class(ASMAT_OT_compile_script)
| mit | 21d5ae286bcd59251ba0ba0c45f9aeaf | 39.442748 | 104 | 0.580974 | 4.59497 | false | false | false | false |
appleseedhq/blenderseed | translators/cycles_shaders.py | 1 | 5153 | #
# This source file is part of appleseed.
# Visit https://appleseedhq.net/ for additional information and resources.
#
# This software is released under the MIT license.
#
# Copyright (c) 2020 Jonathan Dent, The appleseedhq Organization
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import bpy
import numpy as np
cycles_nodes = {"ShaderNodeRGBCurve": "node_rgb_curves.oso",
"ShaderNodeValToRGB": "node_rgb_ramp.oso",
"ShaderNodeSeparateRGB": "node_separate_rgb.oso",
"ShaderNodeCombineRGB": "node_combine_rgb.oso"}
cycles_parameter_mapping = {"ShaderNodeSeparateRGB": {"inputs": ["Image"],
"outputs": ["R", "G", "B"]},
"ShaderNodeCombineRGB": {"inputs": ["R", "G", "B"],
"outputs": ["Image"]},
"ShaderNodeValToRGB": {"inputs": ["Fac"],
"outputs": ["Color", "Alpha"]},
"ShaderNodeRGBCurve": {"inputs": ["Fac", "ColorIn"],
"outputs": ["ColorOut"]}}
def parse_cycles_shader(shader):
if shader.bl_idname == "ShaderNodeRGBCurve":
return parse_ShaderNodeRGBCurve(shader)
elif shader.bl_idname == "ShaderNodeValToRGB":
return parse_ShaderNodeValToRGB(shader)
elif shader.bl_idname == "ShaderNodeSeparateRGB":
return parse_ShaderNodeSeparateRGB()
elif shader.bl_idname == "ShaderNodeCombineRGB":
return parse_ShaderNodeCombineRGB()
def parse_ShaderNodeRGBCurve(shader):
params = dict()
# Curve mapping.
mapping = shader.mapping
mapping.update()
rgb_array = mapping_to_array(mapping)
rgb_string = " ".join(map(str, rgb_array))
params['ramp'] = f"color[] {rgb_string}"
# Additional params.
color_input = list(shader.inputs[1].default_value)
params['ColorIn'] = f"color {color_input[0]} {color_input[1]} {color_input[2]}"
params['Fac'] = f"float {shader.inputs[0].default_value}"
return params
def parse_ShaderNodeValToRGB(shader):
params = dict()
# Interpret color ramp.
ramp = shader.color_ramp
ramp_interpolate = ramp.interpolation != 'CONSTANT'
rgb_array, alpha_array = ramp_to_array(ramp)
rgb_string = " ".join(map(str, rgb_array))
params['ramp_color'] = f"color[] {rgb_string}"
alpha_string = " ".join(map(str, alpha_array))
params['ramp_alpha'] = f"float[] {alpha_string}"
# Additional params.
params['interpolate'] = f"int {int(ramp_interpolate)}"
params['Fac'] = f"float {shader.inputs[0].default_value}"
return params
def parse_ShaderNodeSeparateRGB():
return dict()
def parse_ShaderNodeCombineRGB():
return dict()
def mapping_to_array(mapping):
curve_resolution = bpy.context.preferences.addons['blenderseed'].preferences.curve_resolution
rgb_floats = np.empty(curve_resolution * 3, dtype=float)
map_r = mapping.curves[0]
map_g = mapping.curves[1]
map_b = mapping.curves[2]
map_i = mapping.curves[3]
for i in range(curve_resolution):
start_index = i * 3
t = i / (curve_resolution - 1)
rgb_floats[start_index] = mapping.evaluate(map_r, mapping.evaluate(map_i, t))
rgb_floats[start_index + 1] = mapping.evaluate(map_g, mapping.evaluate(map_i, t))
rgb_floats[start_index + 2] = mapping.evaluate(map_b, mapping.evaluate(map_i, t))
return rgb_floats
def ramp_to_array(ramp):
curve_resolution = bpy.context.preferences.addons['blenderseed'].preferences.curve_resolution
rgb_array = np.empty(curve_resolution * 3, dtype=float)
alpha_array = np.empty(curve_resolution, dtype=float)
for i in range(curve_resolution):
rgb_starting_index = i * 3
color = ramp.evaluate(i / (curve_resolution - 1))
rgb_array[rgb_starting_index] = color[0]
rgb_array[rgb_starting_index + 1] = color[1]
rgb_array[rgb_starting_index + 2] = color[2]
alpha_array[i] = color[3]
return rgb_array, alpha_array
| mit | 88ed61261eaf84f6e9ffa7a4c1da81f4 | 36.889706 | 97 | 0.645837 | 3.715213 | false | false | false | false |
appleseedhq/blenderseed | translators/assethandlers.py | 1 | 5338 | #
# This source file is part of appleseed.
# Visit http://appleseedhq.net/ for additional information and resources.
#
# This software is released under the MIT license.
#
# Copyright (c) 2019 Jonathan Dent, The appleseedhq Organization
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import os
import shutil
from enum import Enum
import bpy
from ..utils.path_util import get_cycles_shader_path, get_osl_search_paths
class AssetType(Enum):
TEXTURE_ASSET = 1
SHADER_ASSET = 2
ARCHIVE_ASSET = 3
class AssetHandler(object):
"""
This class holds methods that are used to translate Blender textures and OSL shader asset filepaths into the correct
format for rendering
"""
def __init__(self, depsgraph):
self._searchpaths = get_osl_search_paths()
self._cycles_osl_path = get_cycles_shader_path()
self._depsgraph = depsgraph
self._searchpaths.append(self._cycles_osl_path)
self._searchpaths.extend(x.name for x in bpy.context.preferences.addons['blenderseed'].preferences.search_paths)
@property
def searchpaths(self):
return self._searchpaths
@property
def cycles_osl_path(self):
return self._cycles_osl_path
def set_searchpath(self, path):
self._searchpaths.append(path)
def process_path(self, filename, asset_type, sub_texture=False):
archive_asset = bpy.path.abspath(filename)
if '%' in archive_asset:
archive_asset = self._convert_frame_number(archive_asset)
if asset_type == AssetType.SHADER_ASSET:
dir_name, file_name = os.path.split(archive_asset)
self._searchpaths.append(dir_name)
archive_asset = os.path.splitext(file_name)[0]
if asset_type == AssetType.TEXTURE_ASSET and sub_texture:
base_filename = os.path.splitext(archive_asset)[0]
archive_asset = f"{base_filename}.tx"
if asset_type == AssetType.ARCHIVE_ASSET:
archive_dir, archive = os.path.split(archive_asset)
self._searchpaths.append(archive_dir)
archive_asset = archive
return archive_asset
def _convert_frame_number(self, file):
base_filename, ext = os.path.splitext(file)
index_1 = base_filename.find("%")
pre_string = base_filename[:index_1]
post_string = base_filename[index_1 + 1:]
number_of_zeroes = int(post_string[:-1])
current_frame = str(self._depsgraph.scene_eval.frame_current)
for zero in range(number_of_zeroes - len(current_frame)):
current_frame = f"0{current_frame}"
return f"{pre_string}{current_frame}{ext}"
class CopyAssetsAssetHandler(AssetHandler):
"""
This class holds methods that are used to translate Blender textures and OSL shader asset filepaths into the correct
format for exported scene files. It also copies texture assets into the correct output folder
"""
def __init__(self, export_dir, geometry_dir, textures_dir, depsgraph):
super(CopyAssetsAssetHandler, self).__init__(depsgraph)
self.__export_dir = export_dir
self.__geometry_dir = geometry_dir
self.__textures_dir = textures_dir
@property
def export_dir(self):
return self.__export_dir
@property
def geometry_dir(self):
return self.__geometry_dir
@property
def textures_dir(self):
return self.__textures_dir
def process_path(self, blend_path, asset_type, sub_texture=False):
original_path = bpy.path.abspath(blend_path)
if '%' in original_path:
original_path = self._convert_frame_number(original_path)
original_dir, filename = os.path.split(original_path)
if asset_type == AssetType.TEXTURE_ASSET:
if sub_texture:
base_filename = os.path.splitext(filename)[0]
filename = f"{base_filename}.tx"
dest_dir = self.textures_dir
dest_file = os.path.join(dest_dir, filename)
if not os.path.exists(dest_file):
shutil.copy(os.path.join(original_dir, filename), os.path.join(dest_dir, filename))
return f"_textures/{filename}"
else:
self._searchpaths.append(original_dir)
return os.path.splitext(filename)[0]
| mit | 9a00e28c2b53e3fd9008ccca67a33582 | 35.561644 | 120 | 0.671975 | 3.925 | false | false | false | false |
appleseedhq/blenderseed | ui/objects.py | 2 | 7091 | #
# This source file is part of appleseed.
# Visit https://appleseedhq.net/ for additional information and resources.
#
# This software is released under the MIT license.
#
# Copyright (c) 2019 Jonathan Dent, The appleseedhq Organization
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import bpy
from ..utils import util
class ASOBJECT_PT_obj_flags(bpy.types.Panel):
bl_label = "appleseed Object Options"
COMPAT_ENGINES = {'APPLESEED_RENDER'}
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "object"
@classmethod
def poll(cls, context):
renderer = context.scene.render
return renderer.engine == 'APPLESEED_RENDER' and context.object is not None and context.object.type in {'MESH', 'CURVE', 'SURFACE', 'EMPTY'}
def draw(self, context):
pass
class ASOBJECT_PT_obj_options(bpy.types.Panel):
bl_label = "Visibility"
COMPAT_ENGINES = {'APPLESEED_RENDER'}
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "object"
bl_parent_id = "ASOBJECT_PT_obj_flags"
@classmethod
def poll(cls, context):
renderer = context.scene.render
return renderer.engine == 'APPLESEED_RENDER' and context.object is not None and context.object.type in {'MESH', 'CURVE', 'SURFACE'}
def draw(self, context):
layout = self.layout
layout.use_property_split = True
asr_obj = context.object.appleseed
sss_lists = context.scene.appleseed_sss_sets
layout.prop(asr_obj, "double_sided", text="Double Sided Shading")
layout.prop(asr_obj, "photon_target", text="SPPM Photon Target")
layout.prop(asr_obj, "medium_priority", text="Nested Glass Priority")
layout.prop(asr_obj, "shadow_terminator_correction", text="Shadow Terminator Fix")
layout.prop_search(asr_obj, "object_sss_set", sss_lists, "sss_sets", text="SSS Set")
class ASOBJECT_PT_obj_visibility(bpy.types.Panel):
bl_label = "Ray Visibility"
COMPAT_ENGINES = {'APPLESEED_RENDER'}
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "object"
bl_parent_id = "ASOBJECT_PT_obj_flags"
@classmethod
def poll(cls, context):
renderer = context.scene.render
return renderer.engine == 'APPLESEED_RENDER' and context.object is not None and context.object.type in {'MESH', 'CURVE', 'SURFACE'}
def draw(self, context):
layout = self.layout
layout.use_property_split = True
asr_obj = context.object.appleseed
layout.prop(asr_obj, "camera_visible", text="Camera")
layout.prop(asr_obj, "light_visible", text="Light")
layout.prop(asr_obj, "shadow_visible", text="Shadow")
layout.prop(asr_obj, "diffuse_visible", text="Diffuse")
layout.prop(asr_obj, "glossy_visible", text="Glossy")
layout.prop(asr_obj, "specular_visible", text="Specular")
layout.prop(asr_obj, "transparency_visible", text="Transparency")
class ASOBJECT_PT_obj_alpha(bpy.types.Panel):
bl_label = "Alpha"
COMPAT_ENGINES = {'APPLESEED_RENDER'}
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "object"
bl_parent_id = "ASOBJECT_PT_obj_flags"
@classmethod
def poll(cls, context):
renderer = context.scene.render
return renderer.engine == 'APPLESEED_RENDER' and context.object is not None and context.object.type in {'MESH', 'CURVE', 'SURFACE'}
def draw(self, context):
layout = self.layout
layout.use_property_split = True
asr_obj = context.object.appleseed
row = layout.row()
row.active = asr_obj.object_alpha_texture is None
row.prop(asr_obj, "object_alpha", text="Object Alpha")
col = layout.column(align=True)
col.template_ID(asr_obj, "object_alpha_texture", open="image.open")
if asr_obj.object_alpha_texture is not None:
as_alpha_tex = asr_obj.object_alpha_texture
col.prop(as_alpha_tex.appleseed, "as_color_space", text="Color Space")
col.prop(as_alpha_tex.appleseed, "as_wrap_mode", text="Wrap Mode")
col.prop(as_alpha_tex.appleseed, "as_alpha_mode", text="Alpha Mode")
class ASOBJECT_PT_motion_blur(bpy.types.Panel):
bl_label = "Motion Blur"
COMPAT_ENGINES = {'APPLESEED_RENDER'}
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "object"
bl_parent_id = "ASOBJECT_PT_obj_flags"
@classmethod
def poll(cls, context):
renderer = context.scene.render
return renderer.engine == 'APPLESEED_RENDER' and context.object is not None and context.object.type in {'MESH', 'CURVE', 'SURFACE'}
def draw(self, context):
layout = self.layout
layout.use_property_split = True
asr_obj = context.object.appleseed
layout.prop(asr_obj, "use_deformation_blur", text="Use Deformation Blur")
class ASOBJECT_PT_export_override(bpy.types.Panel):
bl_label = "Object Export"
COMPAT_ENGINES = {'APPLESEED_RENDER'}
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "object"
bl_parent_id = "ASOBJECT_PT_obj_flags"
@classmethod
def poll(cls, context):
renderer = context.scene.render
return renderer.engine == 'APPLESEED_RENDER' and context.object is not None and context.object.type == 'EMPTY'
def draw(self, context):
layout = self.layout
asr_obj = context.object.appleseed
layout.prop(asr_obj, "object_export", text="Object Export")
row = layout.row()
row.enabled = asr_obj.object_export == 'archive_assembly'
row.prop(asr_obj, "archive_path", text="Archive Path")
classes = (
ASOBJECT_PT_obj_flags,
ASOBJECT_PT_obj_options,
ASOBJECT_PT_obj_visibility,
ASOBJECT_PT_obj_alpha,
ASOBJECT_PT_motion_blur,
ASOBJECT_PT_export_override
)
def register():
for cls in classes:
util.safe_register_class(cls)
def unregister():
for cls in reversed(classes):
util.safe_unregister_class(cls)
| mit | 15936cb48268c1beeb9109c1be194cb9 | 35.551546 | 148 | 0.672966 | 3.37185 | false | false | false | false |
appleseedhq/blenderseed | translators/scene.py | 1 | 42867 | #
# This source file is part of appleseed.
# Visit http://appleseedhq.net/ for additional information and resources.
#
# This software is released under the MIT license.
#
# Copyright (c) 2019 Jonathan Dent, The appleseedhq Organization
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import math
import os
import bpy
import appleseed as asr
from .assethandlers import AssetHandler, CopyAssetsAssetHandler
from .cameras import InteractiveCameraTranslator, RenderCameraTranslator
from .material import MaterialTranslator
from .objects import ArchiveAssemblyTranslator, MeshTranslator, LampTranslator
from .textures import TextureTranslator
from .utilites import ProjectExportMode
from .world import WorldTranslator
from ..logger import get_logger
from ..utils.util import Timer, calc_film_aspect_ratio, clamp_value, realpath
logger = get_logger()
class SceneTranslator(object):
"""
Translates a Blender scene into an appleseed project.
"""
# Constructors.
@classmethod
def create_project_export_translator(cls, depsgraph):
project_dir = os.path.dirname(depsgraph.scene_eval.appleseed.export_path)
logger.debug("Creating texture and geometry directories in %s", project_dir)
geometry_dir = os.path.join(project_dir, "_geometry")
textures_dir = os.path.join(project_dir, "_textures")
if not os.path.exists(geometry_dir):
os.makedirs(geometry_dir)
if not os.path.exists(textures_dir):
os.makedirs(textures_dir)
logger.debug("Creating project export scene translator, filename: %s", depsgraph.scene_eval.appleseed.export_path)
asset_handler = CopyAssetsAssetHandler(project_dir, geometry_dir, textures_dir, depsgraph)
return cls(export_mode=ProjectExportMode.PROJECT_EXPORT,
selected_only=depsgraph.scene.appleseed.export_selected,
asset_handler=asset_handler)
@classmethod
def create_final_render_translator(cls, depsgraph):
"""
Create a scene translator to export the scene to an in memory appleseed project.
:param depsgraph:
:return:
"""
logger.debug("Creating final render scene translator")
asset_handler = AssetHandler(depsgraph)
return cls(export_mode=ProjectExportMode.FINAL_RENDER,
selected_only=False,
asset_handler=asset_handler)
@classmethod
def create_interactive_render_translator(cls, depsgraph):
"""
Create a scene translator to export the scene to an in memory appleseed project
optimized for quick interactive edits.
:param depsgraph:
:return:
"""
logger.debug("Creating interactive render scene translator")
asset_handler = AssetHandler(depsgraph)
return cls(export_mode=ProjectExportMode.INTERACTIVE_RENDER,
selected_only=False,
asset_handler=asset_handler)
def __init__(self, export_mode, selected_only, asset_handler):
"""
Constructor. Do not use it to create instances of this class.
Use the @classmethods instead.
"""
self.__asset_handler = asset_handler
self.__export_mode = export_mode
self.__selected_only = selected_only
# Translators.
self.__as_world_translator = None
self.__as_camera_translator = None
self.__as_object_translators = dict()
self.__as_material_translators = dict()
self.__as_texture_translators = dict()
# Motion Steps.
self.__all_times = {0.0}
self.__cam_times = {0.0}
self.__xform_times = {0.0}
self.__deform_times = {0.0}
# Interactive tools.
self.__viewport_resolution = None
self.__current_frame = None
# Render crop window.
self.__crop_window = None
self.__project = None
self.__frame = None
@property
def as_project(self):
return self.__project
@property
def as_scene(self):
return self.__project.get_scene()
@property
def as_main_assembly(self):
return self.__main_assembly
def translate_scene(self, engine, depsgraph, context=None):
logger.debug("appleseed: Translating scene %s", depsgraph.scene_eval.name)
prof_timer = Timer()
prof_timer.start()
self.__create_project(depsgraph)
if self.__export_mode != ProjectExportMode.INTERACTIVE_RENDER:
self.__calc_shutter_times(depsgraph)
self.__translate_render_settings(depsgraph)
self.__calc_viewport_resolution(depsgraph, context)
aovs = self.__set_aovs(depsgraph)
frame_params = self.__translate_frame(depsgraph)
self.__frame = asr.Frame("beauty", frame_params, aovs)
self.__calc_crop_window(depsgraph, context)
if self.__crop_window is not None:
self.__frame.set_crop_window(self.__crop_window)
if len(depsgraph.scene_eval.appleseed.post_processing_stages) > 0 and self.__export_mode != ProjectExportMode.INTERACTIVE_RENDER:
self.__set_post_process(depsgraph)
self.__project.set_frame(self.__frame)
self.__frame = self.__project.get_frame()
# Create camera
if depsgraph.scene_eval.camera is not None:
# Create interactive or final render camera
if self.__export_mode == ProjectExportMode.INTERACTIVE_RENDER:
self.__as_camera_translator = InteractiveCameraTranslator(depsgraph.scene_eval.camera, self.__asset_handler)
else:
self.__as_camera_translator = RenderCameraTranslator(depsgraph.scene_eval.camera, self.__asset_handler)
else:
engine.error_set("appleseed: No camera in scene!")
# Create world
if depsgraph.scene_eval.world is not None:
self.__as_world_translator = WorldTranslator(depsgraph.scene_eval.world, self.__asset_handler)
# Blender scene processing
objects_to_add = dict()
materials_to_add = dict()
textures_to_add = dict()
for obj in bpy.data.objects:
if obj.type == 'LIGHT':
objects_to_add[obj] = LampTranslator(obj, self.__export_mode, self.__asset_handler)
elif obj.type == 'MESH' and len(obj.data.loops) > 0:
objects_to_add[obj] = MeshTranslator(obj, self.__export_mode, self.__asset_handler)
elif obj.type == 'EMPTY' and obj.appleseed.object_export == "archive_assembly":
objects_to_add[obj] = ArchiveAssemblyTranslator(obj, self.__asset_handler)
for mat in bpy.data.materials:
materials_to_add[mat] = MaterialTranslator(mat, self.__asset_handler)
for tex in bpy.data.images:
if tex.users > 0 and tex.name not in ("Render Result", "Viewer Node"):
textures_to_add[tex] = TextureTranslator(tex, self.__asset_handler)
# Create camera, world, material and texture entities
self.__as_camera_translator.create_entities(depsgraph, context, engine)
if self.__as_world_translator is not None:
self.__as_world_translator.create_entities(depsgraph)
for obj, trans in materials_to_add.items():
trans.create_entities(depsgraph, engine)
for obj, trans in textures_to_add.items():
trans.create_entities(depsgraph)
# Set initial position of all objects and lamps
self.__calc_initial_positions(depsgraph, engine, objects_to_add)
# Remove unused translators
for translator in list(objects_to_add.keys()):
if objects_to_add[translator].instances_size == 0:
del objects_to_add[translator]
# Create 3D entities
for obj, trans in objects_to_add.items():
trans.create_entities(depsgraph, len(self.__deform_times))
# Calculate additional steps for motion blur
if self.__export_mode != ProjectExportMode.INTERACTIVE_RENDER:
self.__calc_motion_steps(depsgraph, engine, objects_to_add)
self.__as_camera_translator.flush_entities(self.as_scene, self.as_main_assembly, self.as_project)
if self.__as_world_translator is not None:
self.__as_world_translator.flush_entities(self.as_scene, self.as_main_assembly, self.as_project)
for obj, trans in objects_to_add.items():
trans.flush_entities(self.as_scene, self.as_main_assembly, self.as_project)
for obj, trans in materials_to_add.items():
trans.flush_entities(self.as_scene, self.as_main_assembly, self.as_project)
for obj, trans in textures_to_add.items():
trans.flush_entities(self.as_scene, self.as_main_assembly, self.as_project)
# Transfer temp translators to main list
for bl_obj, translator in objects_to_add.items():
self.__as_object_translators[bl_obj] = translator
for bl_obj, translator in materials_to_add.items():
self.__as_material_translators[bl_obj] = translator
for bl_obj, translator in textures_to_add.items():
self.__as_texture_translators[bl_obj] = translator
self.__load_searchpaths()
prof_timer.stop()
logger.debug("Scene translated in %f seconds.", prof_timer.elapsed())
def update_multiview_camera(self, engine, depsgraph):
current_frame = depsgraph.scene_eval.frame_current
for time in self.__cam_times:
new_frame = current_frame + time
int_frame = math.floor(new_frame)
subframe = new_frame - int_frame
engine.frame_set(int_frame, subframe=subframe)
self.__as_camera_translator.update_mult_cam_xform(engine, depsgraph.scene_eval, time)
engine.frame_set(current_frame, subframe=0.0)
def update_scene(self, depsgraph, engine):
objects_to_add = dict()
materials_to_add = dict()
object_updates = list()
check_for_deletions = False
recreate_instances = list()
# Check for updated datablocks.
for update in depsgraph.updates:
# This one is easy.
if isinstance(update.id, bpy.types.Material):
if update.id.original in self.__as_material_translators.keys():
self.__as_material_translators[update.id.original].update_material(depsgraph, engine)
else:
materials_to_add[update.id.original] = MaterialTranslator(update.id.original,
self.__asset_handler)
# Now comes agony and mental anguish.
elif isinstance(update.id, bpy.types.Object):
if update.id.type == 'MESH':
if update.id.original in self.__as_object_translators.keys():
if update.is_updated_geometry:
self.__as_object_translators[update.id.original].update_obj_instance()
object_updates.append(update.id.original)
if update.is_updated_transform:
recreate_instances.append(update.id.original)
else:
objects_to_add[update.id.original] = MeshTranslator(update.id.original,
self.__export_mode,
self.__asset_handler)
elif update.id.type == 'LIGHT':
if update.id.original in self.__as_object_translators.keys():
if update.is_updated_geometry:
self.__as_object_translators[update.id.original].update_lamp(depsgraph,
self.as_main_assembly,
self.as_scene,
self.__project)
object_updates.append(update.id.original)
recreate_instances.append(update.id.original)
if update.is_updated_transform:
recreate_instances.append(update.id.original)
else:
objects_to_add[update.id.original] = LampTranslator(update.id.original,
self.__export_mode,
self.__asset_handler)
elif update.id.type == 'EMPTY' and update.id.appleseed.object_export == "archive_assembly":
if update.id.original in self.__as_object_translators.keys():
if update.is_updated_geometry:
self.__as_object_translators[update.id.original].update_archive_ass(depsgraph)
object_updates.append(update.id.original)
if update.is_updated_transform:
recreate_instances.append(update.id.original)
elif isinstance(update.id, bpy.types.World):
self.__as_world_translator.update_world(self.as_scene, depsgraph)
elif isinstance(update.id, bpy.types.Scene):
# Check if world was added or deleted.
# Delete existing world.
if depsgraph.scene_eval.world is None and self.__as_world_translator is not None:
self.__as_world_translator.delete_world(self.as_scene)
self.__as_world_translator = None
# Create new world.
elif depsgraph.scene_eval.world is not None and self.__as_world_translator is None:
self.__as_world_translator = WorldTranslator(depsgraph.scene_eval.world, self.__asset_handler)
self.__as_world_translator.create_entities(depsgraph)
self.__as_world_translator.flush_entities(self.as_scene,
self.as_main_assembly,
self.as_project)
elif isinstance(update.id, bpy.types.Collection):
check_for_deletions = True
# Now we figure out which objects have particle systems that need to have their instances recreated.
for obj in object_updates:
if len(obj.particle_systems) > 0:
for system in obj.particle_systems:
if system.settings.render_type == 'OBJECT':
recreate_instances.append(system.settings.instance_object.original)
elif system.settings.render_type == 'COLLECTION':
for other_obj in system.settings.instance_collection.objects:
if other_obj.type in ('MESH', 'LIGHT') and other_obj.original not in recreate_instances:
recreate_instances.append(other_obj.original)
for obj in recreate_instances:
self.__as_object_translators[obj].clear_instances(self.as_main_assembly)
for inst in depsgraph.object_instances:
if inst.show_self:
obj, inst_id = self.__get_instance_data(inst)
if obj in recreate_instances:
self.__as_object_translators[obj].add_instance_step(0.0, inst_id, inst.matrix_world)
elif obj in objects_to_add.keys():
objects_to_add[obj].add_instance_step(0.0, inst_id, inst.matrix_world)
# Create new materials.
for mat in materials_to_add.values():
mat.create_entities(depsgraph, engine)
# Create new objects.
for trans in objects_to_add.values():
trans.create_entities(depsgraph, 0)
for obj in recreate_instances:
self.__as_object_translators[obj].flush_instances(self.as_main_assembly)
for mat_obj, trans in materials_to_add.items():
trans.flush_entities(self.as_scene, self.as_main_assembly, self.as_project)
self.__as_material_translators[mat_obj] = trans
for bl_obj, trans in objects_to_add.items():
trans.flush_entities(self.as_scene, self.as_main_assembly, self.as_project)
self.__as_object_translators[bl_obj] = trans
# Check if any objects were deleted.
if check_for_deletions:
obj_list = list(self.__as_object_translators.keys())
for obj in obj_list:
try:
if obj.name_full in bpy.data.objects or obj.name_full in bpy.data.lights:
continue
except:
self.__as_object_translators[obj].delete_object(self.as_main_assembly)
del self.__as_object_translators[obj]
def check_view_window(self, depsgraph, context):
# Check if any camera parameters have changed (location, model, etc...)
updates = self.__as_camera_translator.check_for_updates(context, depsgraph.scene_eval)
# Check if frame size has changed.
current_resolution = self.__viewport_resolution
self.__calc_viewport_resolution(depsgraph, context)
updates['frame_size'] = current_resolution != self.__viewport_resolution
# Check if crop window has changed.
current_crop_window = self.__crop_window
self.__calc_crop_window(depsgraph, context)
updates['crop_window'] = current_crop_window != self.__crop_window
return updates
def update_view_window(self, updates, depsgraph):
if updates['cam_model']:
self.__as_camera_translator.update_cam_model(self.as_scene)
self.__as_camera_translator.add_cam_xform(0.0)
else:
if updates['cam_params']:
self.__as_camera_translator.update_cam_params()
if updates['cam_xform']:
self.__as_camera_translator.add_cam_xform(0.0)
if updates['frame_size']:
self.__update_frame_size(depsgraph)
if updates['crop_window']:
self.__frame.reset_crop_window()
if self.__crop_window is not None:
self.__frame.set_crop_window(self.__crop_window)
# Interactive update functions.
def write_project(self, export_path):
# Export project files.
filename = os.path.abspath(bpy.path.ensure_ext(bpy.path.abspath(export_path), '.appleseed'))
asr.ProjectFileWriter().write(self.__project,
filename,
asr.ProjectFileWriterOptions.OmitWritingGeometryFiles | asr.ProjectFileWriterOptions.OmitHandlingAssetFiles)
# Internal methods.
def __create_project(self, depsgraph):
logger.debug("appleseed: Creating appleseed project")
self.__project = asr.Project(depsgraph.scene_eval.name)
# Render settings.
self.__project.add_default_configurations()
# Create the scene.
self.__project.set_scene(asr.Scene())
# Create the environment.
self.as_scene.set_environment(asr.Environment("environment", {}))
# Create the main assembly.
self.as_scene.assemblies().insert(asr.Assembly("assembly", {}))
self.__main_assembly = self.as_scene.assemblies()["assembly"]
# Instance the main assembly.
assembly_inst = asr.AssemblyInstance("assembly_inst", {}, "assembly")
assembly_inst.transform_sequence().set_transform(0.0, asr.Transformd(asr.Matrix4d.identity()))
self.as_scene.assembly_instances().insert(assembly_inst)
# Create default materials.
self.__create_default_material()
self.__create_null_material()
def __create_default_material(self):
logger.debug("appleseed: Creating default material")
surface_shader = asr.SurfaceShader("diagnostic_surface_shader", "__default_surface_shader", {'mode': 'facing_ratio'})
material = asr.Material('generic_material', "__default_material", {'surface_shader': '__default_surface_shader'})
self.as_main_assembly.surface_shaders().insert(surface_shader)
self.as_main_assembly.materials().insert(material)
def __create_null_material(self):
logger.debug("appleseed: Creating null material")
material = asr.Material('generic_material', "__null_material", {})
self.as_main_assembly.materials().insert(material)
def __calc_shutter_times(self, depsgraph):
scene = depsgraph.scene_eval
shutter_length = scene.appleseed.shutter_close - scene.appleseed.shutter_open
if scene.appleseed.enable_camera_blur:
self.__get_sub_frames(
scene, shutter_length, scene.appleseed.camera_blur_samples, self.__cam_times)
if scene.appleseed.enable_object_blur:
self.__get_sub_frames(scene, shutter_length, scene.appleseed.object_blur_samples, self.__xform_times)
if scene.appleseed.enable_deformation_blur:
self.__get_sub_frames(scene,
shutter_length,
self.__round_up_pow2(scene.appleseed.deformation_blur_samples),
self.__deform_times)
# Merge all subframe times
all_times = set()
all_times.update(self.__cam_times)
all_times.update(self.__xform_times)
all_times.update(self.__deform_times)
self.__all_times = sorted(list(all_times))
def __translate_render_settings(self, depsgraph):
logger.debug("appleseed: Translating render settings")
scene = depsgraph.scene_eval
asr_scene_props = scene.appleseed
conf_final = self.__project.configurations()['final']
conf_interactive = self.__project.configurations()['interactive']
lighting_engine = asr_scene_props.lighting_engine if self.__export_mode != ProjectExportMode.INTERACTIVE_RENDER else 'pt'
tile_renderer = 'adaptive' if asr_scene_props.pixel_sampler == 'adaptive' else 'generic'
pixel_render_mapping = {'uniform': 'uniform',
'adaptive': '',
'texture': 'texture'}
pixel_renderer = pixel_render_mapping[asr_scene_props.pixel_sampler]
parameters = {'uniform_pixel_renderer': {'force_antialiasing': True if asr_scene_props.force_aa else False,
'samples': asr_scene_props.samples},
'adaptive_tile_renderer': {'min_samples': asr_scene_props.adaptive_min_samples,
'noise_threshold': asr_scene_props.adaptive_noise_threshold,
'batch_size': asr_scene_props.adaptive_batch_size,
'max_samples': asr_scene_props.adaptive_max_samples},
'texture_controlled_pixel_renderer': {'min_samples': asr_scene_props.adaptive_min_samples,
'max_samples': asr_scene_props.adaptive_max_samples,
'file_path': realpath(asr_scene_props.texture_sampler_filepath)},
'use_embree': asr_scene_props.use_embree,
'pixel_renderer': pixel_renderer,
'lighting_engine': lighting_engine,
'tile_renderer': tile_renderer,
'passes': asr_scene_props.renderer_passes,
'generic_frame_renderer': {'tile_ordering': asr_scene_props.tile_ordering},
'progressive_frame_renderer': {'max_average_spp': asr_scene_props.interactive_max_samples,
'max_fps': asr_scene_props.interactive_max_fps,
'time_limit': asr_scene_props.interactive_max_time},
'light_sampler': {'algorithm': asr_scene_props.light_sampler,
'enable_light_importance_sampling': asr_scene_props.enable_light_importance_sampling},
'shading_result_framebuffer': "permanent" if asr_scene_props.renderer_passes > 1 else "ephemeral"}
if self.__export_mode != ProjectExportMode.PROJECT_EXPORT:
if self.__export_mode == ProjectExportMode.INTERACTIVE_RENDER:
render_threads = -1
else:
render_threads = asr_scene_props.threads if not asr_scene_props.threads_auto else 'auto'
parameters['rendering_threads'] = render_threads
parameters['texture_store'] = {'max_size': asr_scene_props.tex_cache * 1024 * 1024}
if lighting_engine == 'pt':
parameters['pt'] = {'enable_ibl': True if asr_scene_props.enable_ibl else False,
'enable_dl': True if asr_scene_props.enable_dl else False,
'enable_caustics': True if scene.appleseed.enable_caustics else False,
'clamp_roughness': True if scene.appleseed.enable_clamp_roughness else False,
'record_light_paths': True if scene.appleseed.record_light_paths else False,
'next_event_estimation': True,
'rr_min_path_length': asr_scene_props.rr_start,
'optimize_for_lights_outside_volumes': asr_scene_props.optimize_for_lights_outside_volumes,
'volume_distance_samples': asr_scene_props.volume_distance_samples,
'dl_light_samples': asr_scene_props.dl_light_samples,
'ibl_env_samples': asr_scene_props.ibl_env_samples,
'dl_low_light_threshold': asr_scene_props.dl_low_light_threshold,
'max_diffuse_bounces': asr_scene_props.max_diffuse_bounces if not asr_scene_props.max_diffuse_bounces_unlimited else -1,
'max_glossy_bounces': asr_scene_props.max_glossy_brdf_bounces if not asr_scene_props.max_glossy_brdf_bounces_unlimited else -1,
'max_specular_bounces': asr_scene_props.max_specular_bounces if not asr_scene_props.max_specular_bounces_unlimited else -1,
'max_volume_bounces': asr_scene_props.max_volume_bounces if not asr_scene_props.max_volume_bounces_unlimited else -1,
'max_bounces': asr_scene_props.max_bounces if not asr_scene_props.max_bounces_unlimited else -1}
if not asr_scene_props.max_ray_intensity_unlimited:
parameters['pt']['max_ray_intensity'] = asr_scene_props.max_ray_intensity
else:
parameters['sppm'] = {'alpha': asr_scene_props.sppm_alpha,
'dl_mode': asr_scene_props.sppm_dl_mode,
'enable_caustics': "true" if asr_scene_props.enable_caustics else "false",
'env_photons_per_pass': asr_scene_props.sppm_env_photons,
'initial_radius': asr_scene_props.sppm_initial_radius,
'light_photons_per_pass': asr_scene_props.sppm_light_photons,
# Leave at 0 for now - not in appleseed.studio GUI
'max_path_length': 0,
'enable_importons': asr_scene_props.sppm_enable_importons,
'importon_lookup_radius': asr_scene_props.sppm_importon_lookup_radius,
'max_photons_per_estimate': asr_scene_props.sppm_max_per_estimate,
'path_tracing_max_path_length': asr_scene_props.sppm_pt_max_length,
'path_tracing_rr_min_path_length': asr_scene_props.sppm_pt_rr_start,
'photon_tracing_max_path_length': asr_scene_props.sppm_photon_max_length,
'photon_tracing_rr_min_path_length': asr_scene_props.sppm_photon_rr_start}
if not asr_scene_props.sppm_pt_max_ray_intensity_unlimited:
parameters['sppm']['path_tracing_max_ray_intensity'] = asr_scene_props.sppm_pt_max_ray_intensity
if asr_scene_props.shading_override:
parameters['shading_engine'] = {'override_shading': {'mode': asr_scene_props.override_mode}}
conf_final.set_parameters(parameters)
parameters['lighting_engine'] = 'pt'
conf_interactive.set_parameters(parameters)
def __calc_viewport_resolution(self, depsgraph, context):
scene = depsgraph.scene_eval
scale = scene.render.resolution_percentage / 100.0
if context is not None:
width = int(context.region.width)
height = int(context.region.height)
else:
width = int(scene.render.resolution_x * scale)
height = int(scene.render.resolution_y * scale)
self.__viewport_resolution = [width, height]
def __translate_frame(self, depsgraph):
logger.debug("appleseed: Translating frame")
scene = depsgraph.scene_eval
asr_scene_props = scene.appleseed
noise_seed = (asr_scene_props.noise_seed + scene.frame_current) if asr_scene_props.per_frame_noise else asr_scene_props.noise_seed
width, height = self.__viewport_resolution
frame_params = {'resolution': asr.Vector2i(width, height),
'camera': "Camera",
'filter': asr_scene_props.pixel_filter,
'filter_size': asr_scene_props.pixel_filter_size,
'denoiser': asr_scene_props.denoise_mode,
'noise_seed': noise_seed,
'skip_denoised': asr_scene_props.skip_denoised,
'random_pixel_order': asr_scene_props.random_pixel_order,
'prefilter_spikes': asr_scene_props.prefilter_spikes,
'spike_threshold': asr_scene_props.spike_threshold,
'patch_distance_threshold': asr_scene_props.patch_distance_threshold,
'denoise_scales': asr_scene_props.denoise_scales,
'mark_invalid_pixels': asr_scene_props.mark_invalid_pixels}
if self.__export_mode != ProjectExportMode.PROJECT_EXPORT:
frame_params['tile_size'] = asr.Vector2i(asr_scene_props.tile_size, asr_scene_props.tile_size)
return frame_params
def __calc_crop_window(self, depsgraph, context=None):
width, height = self.__viewport_resolution
self.__crop_window = None
if depsgraph.scene_eval.render.use_border and self.__export_mode != ProjectExportMode.INTERACTIVE_RENDER:
min_x = int(depsgraph.scene_eval.render.border_min_x * width)
min_y = height - int(depsgraph.scene_eval.render.border_max_y * height)
max_x = int(depsgraph.scene_eval.render.border_max_x * width) - 1
max_y = height - int(depsgraph.scene_eval.render.border_min_y * height) - 1
self.__crop_window = [min_x,
min_y,
max_x,
max_y]
else:
# Interactive render borders
if context is not None and context.space_data.use_render_border and context.region_data.view_perspective in ('ORTHO', 'PERSP'):
min_x = int(context.space_data.render_border_min_x * width)
min_y = height - int(context.space_data.render_border_max_y * height)
max_x = int(context.space_data.render_border_max_x * width) - 1
max_y = height - int(context.space_data.render_border_min_y * height) - 1
self.__crop_window = [min_x,
min_y,
max_x,
max_y]
elif depsgraph.scene_eval.render.use_border and context.region_data.view_perspective == 'CAMERA':
"""
I can't explain how the following code produces the correct render window.
I basically threw every parameter combination I could think of together
until the result looked right.
"""
zoom = 4 / ((math.sqrt(2) + context.region_data.view_camera_zoom / 50) ** 2)
frame_aspect_ratio = width / height
camera_aspect_ratio = calc_film_aspect_ratio(depsgraph.scene_eval)
if frame_aspect_ratio > 1:
camera_width = width / zoom
camera_height = camera_width / camera_aspect_ratio
else:
camera_height = height / (zoom * camera_aspect_ratio)
camera_width = camera_height * camera_aspect_ratio
view_offset_x, view_offset_y = context.region_data.view_camera_offset
view_shift_x = ((view_offset_x * 2) / zoom) * width
view_shift_y = ((view_offset_y * 2) / zoom) * height
window_shift_x = (width - camera_width) / 2
window_shift_y = (height - camera_height) / 2
window_x_min = int(camera_width * depsgraph.scene_eval.render.border_min_x + window_shift_x - view_shift_x)
window_x_max = int(camera_width * depsgraph.scene_eval.render.border_max_x + window_shift_x - view_shift_x)
window_y_min = height - int(camera_height * depsgraph.scene_eval.render.border_max_y + window_shift_y - view_shift_y)
window_y_max = height - int(camera_height * depsgraph.scene_eval.render.border_min_y + window_shift_y - view_shift_y)
# Check for coordinates outside the render window.
min_x = clamp_value(window_x_min, 0, width - 1)
min_y = clamp_value(window_y_min, 0, height - 1)
max_x = clamp_value(window_x_max, 0, width - 1)
max_y = clamp_value(window_y_max, 0, height - 1)
self.__crop_window = [min_x,
min_y,
max_x,
max_y]
def __set_aovs(self, depsgraph):
logger.debug("appleseed: Translating AOVs")
asr_scene_props = depsgraph.scene_eval.appleseed
aovs = asr.AOVContainer()
if self.__export_mode != ProjectExportMode.INTERACTIVE_RENDER:
if asr_scene_props.albedo_aov:
aovs.insert(asr.AOV('albedo_aov', {}))
if asr_scene_props.diffuse_aov:
aovs.insert(asr.AOV('diffuse_aov', {}))
if asr_scene_props.direct_diffuse_aov:
aovs.insert(asr.AOV('direct_diffuse_aov', {}))
if asr_scene_props.direct_glossy_aov:
aovs.insert(asr.AOV('direct_glossy_aov', {}))
if asr_scene_props.emission_aov:
aovs.insert(asr.AOV('emission_aov', {}))
if asr_scene_props.glossy_aov:
aovs.insert(asr.AOV('glossy_aov', {}))
if asr_scene_props.indirect_diffuse_aov:
aovs.insert(asr.AOV('indirect_diffuse_aov', {}))
if asr_scene_props.indirect_glossy_aov:
aovs.insert(asr.AOV('indirect_glossy_aov', {}))
if asr_scene_props.invalid_samples_aov:
aovs.insert(asr.AOV('invalid_samples_aov', {}))
if asr_scene_props.normal_aov:
aovs.insert(asr.AOV('normal_aov', {}))
if asr_scene_props.npr_contour_aov:
aovs.insert(asr.AOV('npr_contour_aov', {}))
if asr_scene_props.npr_shading_aov:
aovs.insert(asr.AOV('npr_shading_aov', {}))
if asr_scene_props.pixel_sample_count_aov:
aovs.insert(asr.AOV('pixel_sample_count_aov', {}))
if asr_scene_props.pixel_time_aov:
aovs.insert(asr.AOV('pixel_time_aov', {}))
if asr_scene_props.pixel_variation_aov:
aovs.insert(asr.AOV('pixel_variation_aov', {}))
if asr_scene_props.position_aov:
aovs.insert(asr.AOV('position_aov', {}))
if asr_scene_props.screen_space_velocity_aov:
aovs.insert(asr.AOV('screen_space_velocity_aov', {}))
if asr_scene_props.uv_aov:
aovs.insert(asr.AOV('uv_aov', {}))
if asr_scene_props.cryptomatte_material_aov:
aovs.insert(asr.AOV('cryptomatte_material_aov', {}))
if asr_scene_props.cryptomatte_object_aov:
aovs.insert(asr.AOV('cryptomatte_object_aov', {}))
return aovs
def __set_post_process(self, depsgraph):
asr_scene_props = depsgraph.scene_eval.appleseed
for index, stage in enumerate(asr_scene_props.post_processing_stages):
if stage.model == 'render_stamp_post_processing_stage':
params = {'order': index, 'format_string': stage.render_stamp}
else:
params = {'order': index,
'color_map': stage.color_map,
'auto_range': stage.auto_range,
'range_min': stage.range_min,
'range_max': stage.range_max,
'add_legend_bar': stage.add_legend_bar,
'legend_bar_ticks': stage.legend_bar_ticks,
'render_isolines': stage.render_isolines,
'line_thickness': stage.line_thickness}
if stage.color_map == 'custom':
params['color_map_file_path'] = stage.color_map_file_path
post_process = asr.PostProcessingStage(stage.model, stage.name, params)
logger.debug("Adding Post Process: %s", stage.name)
self.__frame.post_processing_stages().insert(post_process)
def __calc_initial_positions(self, depsgraph, engine, objects_to_add):
logger.debug("appleseed: Setting intial object positions for frame %s", depsgraph.scene_eval.frame_current)
self.__as_camera_translator.add_cam_xform(0.0, engine)
for inst in depsgraph.object_instances:
if inst.show_self:
obj, inst_id = self.__get_instance_data(inst)
if obj in objects_to_add.keys():
objects_to_add[obj].add_instance_step(0.0, inst_id, inst.matrix_world)
def __calc_motion_steps(self, depsgraph, engine, objects_to_add):
self.__current_frame = depsgraph.scene_eval.frame_current
logger.debug("appleseed: Processing motion steps for frame %s", self.__current_frame)
for index, time in enumerate(self.__all_times[1:]):
new_frame = self.__current_frame + time
int_frame = math.floor(new_frame)
subframe = new_frame - int_frame
engine.frame_set(int_frame, subframe=subframe)
if time in self.__cam_times:
self.__as_camera_translator.add_cam_xform(time, engine)
if time in self.__xform_times:
for inst in depsgraph.object_instances:
if inst.show_self:
obj, inst_id = self.__get_instance_data(inst)
if obj in objects_to_add.keys():
objects_to_add[obj].add_instance_step(time, inst_id, inst.matrix_world)
if time in self.__deform_times:
for translator in objects_to_add.values():
translator.set_deform_key(time, depsgraph, index)
engine.frame_set(self.__current_frame, subframe=0.0)
def __load_searchpaths(self):
logger.debug("appleseed: Loading searchpaths")
paths = self.__project.get_search_paths()
paths.extend(path for path in self.__asset_handler.searchpaths if path not in paths)
self.__project.set_search_paths(paths)
def __update_frame_size(self, depsgraph):
frame_params = self.__translate_frame(depsgraph)
self.__frame = asr.Frame("beauty", frame_params, asr.AOVContainer())
self.__project.set_frame(self.__frame)
self.__frame = self.__project.get_frame()
# Static utility methods
@staticmethod
def __get_sub_frames(scene, shutter_length, samples, times):
assert samples > 1
segment_size = shutter_length / (samples - 1)
for seg in range(0, samples):
times.update({scene.appleseed.shutter_open + (seg * segment_size)})
@staticmethod
def __get_instance_data(instance):
if instance.is_instance: # Instance was generated by a particle system or dupli object.
obj = instance.instance_object.original
inst_id = f"{obj.appleseed.obj_name}|{instance.parent.original.name_full}|{instance.persistent_id[0]}"
else: # Instance is a discreet object in the scene.
obj = instance.object.original
inst_id = f"{obj.appleseed.obj_name}|{instance.persistent_id[0]}"
return obj, inst_id
@staticmethod
def __round_up_pow2(deformation_blur_samples):
assert (deformation_blur_samples >= 2)
return 1 << (deformation_blur_samples - 1).bit_length()
| mit | 1453228d1eeb447ee62b91a75afba88d | 47.273649 | 159 | 0.582826 | 4.028475 | false | false | false | false |
mbi/django-rosetta | rosetta/access.py | 1 | 2502 | import importlib
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .conf import settings as rosetta_settings
def can_translate(user):
return get_access_control_function()(user)
def get_access_control_function():
"""
Return a predicate for determining if a user can
access the Rosetta views
"""
access_function = getattr(settings, 'ROSETTA_ACCESS_CONTROL_FUNCTION', None)
if access_function is None:
return is_superuser_staff_or_in_translators_group
elif isinstance(access_function, str):
# Dynamically load a permissions function
perm_module, perm_func = access_function.rsplit('.', 1)
perm_module = importlib.import_module(perm_module)
return getattr(perm_module, perm_func)
elif callable(access_function):
return access_function
else:
raise TypeError(access_function)
# Default access control test
def is_superuser_staff_or_in_translators_group(user):
if not getattr(settings, 'ROSETTA_REQUIRES_AUTH', True):
return True
try:
if not user.is_authenticated:
return False
elif user.is_superuser and user.is_staff:
return True
else:
return user.groups.filter(name='translators').exists()
except AttributeError:
if not hasattr(user, 'is_authenticated') or not hasattr(user, 'is_superuser') or not hasattr(user, 'groups'):
raise ImproperlyConfigured('If you are using custom User Models you must implement a custom authentication method for Rosetta. See ROSETTA_ACCESS_CONTROL_FUNCTION here: https://django-rosetta.readthedocs.org/en/latest/settings.html')
raise
def can_translate_language(user, langid):
try:
if not rosetta_settings.ROSETTA_LANGUAGE_GROUPS:
return can_translate(user)
elif not user.is_authenticated:
return False
elif user.is_superuser and user.is_staff:
return True
else:
return user.groups.filter(name='translators-%s' % langid).exists()
except AttributeError:
if not hasattr(user, 'is_authenticated') or not hasattr(user, 'is_superuser') or not hasattr(user, 'groups'):
raise ImproperlyConfigured('If you are using custom User Models you must implement a custom authentication method for Rosetta. See ROSETTA_ACCESS_CONTROL_FUNCTION here: https://django-rosetta.readthedocs.org/en/latest/settings.html')
raise
| mit | acd8ae2cfbffab73a8e592584a9bd81f | 38.714286 | 245 | 0.692246 | 4.17 | false | false | false | false |
rkhleics/wagtailmenus | wagtailmenus/models/pages.py | 2 | 11199 | from copy import copy
from io import StringIO
from django.conf import settings as django_settings
from django.core.exceptions import ValidationError
from django.db import models
from django.http import HttpResponse
from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _
from wagtail.core.models import Page
from wagtailmenus.conf import settings
from wagtailmenus.forms import LinkPageAdminForm
from wagtailmenus.panels import menupage_settings_panels, linkpage_edit_handler
class MenuPageMixin(models.Model):
repeat_in_subnav = models.BooleanField(
verbose_name=_("repeat in sub-navigation"),
default=False,
help_text=_(
"If checked, a link to this page will be repeated alongside it's "
"direct children when displaying a sub-navigation for this page."
),
)
repeated_item_text = models.CharField(
verbose_name=_('repeated item link text'),
max_length=255,
blank=True,
help_text=_(
"e.g. 'Section home' or 'Overview'. If left blank, the page title "
"will be used."
)
)
class Meta:
abstract = True
def modify_submenu_items(
self, menu_items, current_page, current_ancestor_ids, current_site,
allow_repeating_parents, apply_active_classes, original_menu_tag,
menu_instance=None, request=None, use_absolute_page_urls=False,
):
"""
Make any necessary modifications to `menu_items` and return the list
back to the calling menu tag to render in templates. Any additional
items added should have a `text` and `href` attribute as a minimum.
`original_menu_tag` should be one of 'main_menu', 'section_menu' or
'children_menu', which should be useful when extending/overriding.
"""
if (allow_repeating_parents and menu_items and self.repeat_in_subnav):
"""
This page should have a version of itself repeated alongside
children in the subnav, so we create a new item and prepend it to
menu_items.
"""
repeated_item = self.get_repeated_menu_item(
current_page=current_page,
current_site=current_site,
apply_active_classes=apply_active_classes,
original_menu_tag=original_menu_tag,
use_absolute_page_urls=use_absolute_page_urls,
request=request,
)
menu_items.insert(0, repeated_item)
return menu_items
def has_submenu_items(self, current_page, allow_repeating_parents,
original_menu_tag, menu_instance=None, request=None):
"""
When rendering pages in a menu template a `has_children_in_menu`
attribute is added to each page, letting template developers know
whether or not the item has a submenu that must be rendered.
By default, we return a boolean indicating whether the page has
suitable child pages to include in such a menu. But, if you are
overriding the `modify_submenu_items` method to programatically add
items that aren't child pages, you'll likely need to alter this method
too, so the template knows there are sub items to be rendered.
"""
return menu_instance.page_has_children(self)
def get_text_for_repeated_menu_item(
self, request=None, current_site=None, original_menu_tag='', **kwargs
):
"""Return the a string to use as 'text' for this page when it is being
included as a 'repeated' menu item in a menu. You might want to
override this method if you're creating a multilingual site and you
have different translations of 'repeated_item_text' that you wish to
surface."""
source_field_name = settings.PAGE_FIELD_FOR_MENU_ITEM_TEXT
return self.repeated_item_text or getattr(
self, source_field_name, self.title
)
def get_repeated_menu_item(
self, current_page, current_site, apply_active_classes,
original_menu_tag, request=None, use_absolute_page_urls=False,
):
"""Return something that can be used to display a 'repeated' menu item
for this specific page."""
menuitem = copy(self)
# Set/reset 'text'
menuitem.text = self.get_text_for_repeated_menu_item(
request, current_site, original_menu_tag
)
# Set/reset 'href'
if use_absolute_page_urls:
url = self.get_full_url(request=request)
else:
url = self.relative_url(current_site)
menuitem.href = url
# Set/reset 'active_class'
if apply_active_classes and self == current_page:
menuitem.active_class = settings.ACTIVE_CLASS
else:
menuitem.active_class = ''
# Set/reset 'has_children_in_menu' and 'sub_menu'
menuitem.has_children_in_menu = False
menuitem.sub_menu = None
return menuitem
class MenuPage(Page, MenuPageMixin):
settings_panels = menupage_settings_panels
class Meta:
abstract = True
class AbstractLinkPage(Page):
link_page = models.ForeignKey(
'wagtailcore.Page',
verbose_name=_('link to an internal page'),
blank=True,
null=True,
related_name='+',
on_delete=models.SET_NULL,
)
link_url = models.CharField(
verbose_name=_('link to a custom URL'),
max_length=255,
blank=True,
null=True,
)
url_append = models.CharField(
verbose_name=_("append to URL"),
max_length=255,
blank=True,
help_text=_(
"Use this to optionally append a #hash or querystring to the URL."
)
)
extra_classes = models.CharField(
verbose_name=_('menu item css classes'),
max_length=100,
blank=True,
help_text=_(
"Optionally specify css classes to be added to this page when it "
"appears in menus."
)
)
subpage_types = [] # Don't allow subpages
search_fields = [] # Don't surface these pages in search results
base_form_class = LinkPageAdminForm
class Meta:
abstract = True
def __init__(self, *args, **kwargs):
# Set `show_in_menus` to True by default, but leave as False if
# it has been set
super().__init__(*args, **kwargs)
if not self.pk:
self.show_in_menus = True
def menu_text(self, request=None):
"""Return a string to use as link text when this page appears in
menus."""
source_field_name = settings.PAGE_FIELD_FOR_MENU_ITEM_TEXT
if(
source_field_name != 'menu_text' and
hasattr(self, source_field_name)
):
return getattr(self, source_field_name)
return self.title
def clean(self, *args, **kwargs):
if self.link_page and isinstance(
self.link_page.specific, AbstractLinkPage
):
raise ValidationError({
'link_page': ValidationError(
_("A link page cannot link to another link page"),
code='invalid'
),
})
if not self.link_url and not self.link_page:
raise ValidationError(
_("Please choose an internal page or provide a custom URL"),
code='invalid'
)
if self.link_url and self.link_page:
raise ValidationError(
_("Linking to both a page and custom URL is not permitted"),
code='invalid'
)
super().clean(*args, **kwargs)
def link_page_is_suitable_for_display(
self, request=None, current_site=None, menu_instance=None,
original_menu_tag=''
):
"""
Like menu items, link pages linking to pages should only be included
in menus when the target page is live and is itself configured to
appear in menus. Returns a boolean indicating as much
"""
if self.link_page:
if(
not self.link_page.show_in_menus or
not self.link_page.live or
self.link_page.expired
):
return False
return True
def show_in_menus_custom(self, request=None, current_site=None,
menu_instance=None, original_menu_tag=''):
"""
Return a boolean indicating whether this page should be included in
menus being rendered.
"""
if not self.show_in_menus:
return False
if self.link_page:
return self.link_page_is_suitable_for_display()
return True
def get_sitemap_urls(self, request=None):
return [] # don't include pages of this type in sitemaps
def _url_base(self, request=None, current_site=None, full_url=False):
# Return the url of the page being linked to, or the custom URL
if self.link_url:
return self.link_url
if not self.link_page:
return ''
p = self.link_page.specific # for tidier referencing below
if full_url:
return p.get_full_url(request=request)
return p.get_url(request=request, current_site=current_site)
def get_url(self, request=None, current_site=None):
try:
base = self._url_base(request=request, current_site=current_site)
return base + self.url_append
except TypeError:
pass # self.link_page is not routable
return ''
url = property(get_url)
def get_full_url(self, request=None):
try:
base = self._url_base(request=request, full_url=True)
return base + self.url_append
except TypeError:
pass # self.link_page is not routable
return ''
full_url = property(get_full_url)
def relative_url(self, current_site, request=None):
return self.get_url(request=request, current_site=current_site)
def serve(self, request, *args, **kwargs):
# Display appropriate message if previewing
if getattr(request, 'is_preview', False):
return HttpResponse(_("This page redirects to: %(url)s") % {
'url': self.get_full_url(request)
})
# Redirect to target URL if served
site = getattr(request, 'site', None)
return redirect(
self.relative_url(current_site=site, request=request)
)
def _get_dummy_header_url(self, original_request=None):
"""
Overrides Page._get_dummy_header_url() (added in Wagtail 2.7) to avoid
creating dummy headers from full_url(), which, in the case of a link
page, could be for a different domain (which would likely result in
a 400 error if ALLOWED_HOSTS is not ['*']).
"""
if original_request:
return original_request.build_absolute_uri()
return super()._get_dummy_header_url(original_request)
edit_handler = linkpage_edit_handler
| mit | d88d70c18c2aca82db856c26735e697c | 35.009646 | 79 | 0.604072 | 4.21015 | false | false | false | false |
rkhleics/wagtailmenus | wagtailmenus/modeladmin.py | 2 | 4086 | from django.conf.urls import url
from django.contrib.admin.utils import quote
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from wagtail.contrib.modeladmin.options import ModelAdmin
from wagtail.contrib.modeladmin.helpers import ButtonHelper
from wagtailmenus.conf import settings
from wagtailmenus import views
class MainMenuAdmin(ModelAdmin):
model = settings.models.MAIN_MENU_MODEL
menu_label = _('Main menu')
menu_icon = settings.MAINMENU_MENU_ICON
index_view_class = views.MainMenuIndexView
edit_view_class = views.MainMenuEditView
add_to_settings_menu = True
def get_form_view_extra_css(self):
if settings.ADD_EDITOR_OVERRIDE_STYLES:
return ['wagtailmenus/css/menu-edit.css']
return []
def get_admin_urls_for_registration(self):
return (
url(self.url_helper.get_action_url_pattern('index'),
self.index_view,
name=self.url_helper.get_action_url_name('index')),
url(self.url_helper.get_action_url_pattern('edit'),
self.edit_view,
name=self.url_helper.get_action_url_name('edit')),
)
class FlatMenuButtonHelper(ButtonHelper):
def copy_button(self, pk, classnames_add=[], classnames_exclude=[]):
cn = self.finalise_classname(classnames_add, classnames_exclude)
return {
'url': self.url_helper.get_action_url('copy', quote(pk)),
'label': _('Copy'),
'classname': cn,
'title': _('Copy this %(model_name)s') % {
'model_name': self.verbose_name,
},
}
def get_buttons_for_obj(self, obj, exclude=[], classnames_add=[],
classnames_exclude=[]):
ph = self.permission_helper
usr = self.request.user
pk = quote(getattr(obj, self.opts.pk.attname))
btns = super().get_buttons_for_obj(
obj, exclude, classnames_add, classnames_exclude)
if('copy' not in exclude and ph.user_can_create(usr)):
btns.append(
self.copy_button(pk, classnames_add, classnames_exclude)
)
return btns
class FlatMenuAdmin(ModelAdmin):
model = settings.models.FLAT_MENU_MODEL
menu_label = _('Flat menus')
menu_icon = settings.FLATMENU_MENU_ICON
button_helper_class = FlatMenuButtonHelper
ordering = ('-site__is_default_site', 'site__hostname', 'handle')
create_view_class = views.FlatMenuCreateView
edit_view_class = views.FlatMenuEditView
add_to_settings_menu = True
def get_form_view_extra_css(self):
if settings.ADD_EDITOR_OVERRIDE_STYLES:
return ['wagtailmenus/css/menu-edit.css']
return []
def copy_view(self, request, instance_pk):
kwargs = {'model_admin': self, 'instance_pk': instance_pk}
return views.FlatMenuCopyView.as_view(**kwargs)(request)
def get_admin_urls_for_registration(self):
urls = super().get_admin_urls_for_registration()
urls += (
url(self.url_helper.get_action_url_pattern('copy'),
self.copy_view,
name=self.url_helper.get_action_url_name('copy')),
)
return urls
def get_list_filter(self, request):
if self.is_multisite_listing(request):
return ('site', 'handle')
return ()
def get_list_display(self, request):
if self.is_multisite_listing(request):
return ('title', 'handle_formatted', 'site', 'items')
return ('title', 'handle_formatted', 'items')
def handle_formatted(self, obj):
return mark_safe('<code>%s</code>' % obj.handle)
handle_formatted.short_description = _('handle')
handle_formatted.admin_order_field = 'handle'
def is_multisite_listing(self, request):
return self.get_queryset(request).values('site').distinct().count() > 1
def items(self, obj):
return obj.get_menu_items_manager().count()
items.short_description = _('no. of items')
| mit | b71ad03aa255af81b6f11c3ba3aee73d | 35.810811 | 79 | 0.625551 | 3.783333 | false | false | false | false |
rkhleics/wagtailmenus | wagtailmenus/tests/migrations/0001_initial.py | 3 | 1569 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-17 19:20
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('wagtailcore', '0028_merge'),
]
operations = [
migrations.CreateModel(
name='LowLevelPage',
fields=[
('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
],
options={
'abstract': False,
},
bases=('wagtailcore.page',),
),
migrations.CreateModel(
name='TopLevelPage',
fields=[
('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
('repeat_in_subnav', models.BooleanField(default=False, verbose_name='Include a link to this page alongside children when displaying sub-navigation')),
('subnav_menu_text', models.CharField(blank=True, help_text="e.g. 'Section home' or 'Overview'. If left blank, the page title will be used.", max_length=255, verbose_name='Link text for sub-navigation item')),
],
options={
'abstract': False,
},
bases=('wagtailcore.page',),
),
]
| mit | f14389f5c86f7b99524bd84ff8b6cb9b | 38.225 | 225 | 0.597196 | 4.286885 | false | false | false | false |
mbi/django-rosetta | rosetta/conf/__init__.py | 1 | 4382 | """
For a description of each rosetta setting see: docs/settings.rst.
"""
from django.conf import settings as dj_settings
from django.core.signals import setting_changed
__all__ = ['settings']
class RosettaSettings(object):
"""
Class that holds rosetta settings.
The settings object is an instance of this class and is reloaded when
the ``setting_changed`` signal is dispatched.
"""
SETTINGS = {
'ROSETTA_MESSAGES_PER_PAGE': ('MESSAGES_PER_PAGE', 10),
'ROSETTA_ENABLE_TRANSLATION_SUGGESTIONS': (
'ENABLE_TRANSLATION_SUGGESTIONS',
False,
),
'YANDEX_TRANSLATE_KEY': ('YANDEX_TRANSLATE_KEY', None),
'AZURE_CLIENT_SECRET': ('AZURE_CLIENT_SECRET', None),
'GOOGLE_APPLICATION_CREDENTIALS_PATH': (
'GOOGLE_APPLICATION_CREDENTIALS_PATH',
None,
),
'GOOGLE_PROJECT_ID': ('GOOGLE_PROJECT_ID', None),
'DEEPL_AUTH_KEY': ('DEEPL_AUTH_KEY', None),
'ROSETTA_MAIN_LANGUAGE': ('MAIN_LANGUAGE', None),
'ROSETTA_MESSAGES_SOURCE_LANGUAGE_CODE': ('MESSAGES_SOURCE_LANGUAGE_CODE', 'en'),
'ROSETTA_MESSAGES_SOURCE_LANGUAGE_NAME': (
'MESSAGES_SOURCE_LANGUAGE_NAME',
'English',
),
'ROSETTA_ACCESS_CONTROL_FUNCTION': ('ACCESS_CONTROL_FUNCTION', None),
'ROSETTA_WSGI_AUTO_RELOAD': ('WSGI_AUTO_RELOAD', False),
'ROSETTA_UWSGI_AUTO_RELOAD': ('UWSGI_AUTO_RELOAD', False),
'ROSETTA_EXCLUDED_APPLICATIONS': ('EXCLUDED_APPLICATIONS', ()),
'ROSETTA_POFILE_WRAP_WIDTH': ('POFILE_WRAP_WIDTH', 78),
'ROSETTA_STORAGE_CLASS': ('STORAGE_CLASS', 'rosetta.storage.CacheRosettaStorage'),
'ROSETTA_ENABLE_REFLANG': ('ENABLE_REFLANG', False),
'ROSETTA_POFILENAMES': ('POFILENAMES', ('django.po', 'djangojs.po')),
'ROSETTA_CACHE_NAME': (
'ROSETTA_CACHE_NAME',
'rosetta' if 'rosetta' in dj_settings.CACHES else 'default',
),
'ROSETTA_REQUIRES_AUTH': ('ROSETTA_REQUIRES_AUTH', True),
'ROSETTA_EXCLUDED_PATHS': ('ROSETTA_EXCLUDED_PATHS', ()),
'ROSETTA_LANGUAGE_GROUPS': ('ROSETTA_LANGUAGE_GROUPS', False),
'ROSETTA_AUTO_COMPILE': ('AUTO_COMPILE', True),
'ROSETTA_SHOW_AT_ADMIN_PANEL': ('SHOW_AT_ADMIN_PANEL', False),
'ROSETTA_LOGIN_URL': ('LOGIN_URL', dj_settings.LOGIN_URL),
'ROSETTA_LANGUAGES': ('ROSETTA_LANGUAGES', dj_settings.LANGUAGES),
'ROSETTA_SHOW_OCCURRENCES': ('SHOW_OCCURRENCES', True),
# Deepl API language codes are different then those of django, so if this is not set according to your desired languages,
# We use the first 2 letters of django language code.
# In which case it would work fine for most of the languages,
# But for 'en' if you want "EN-GB" for example, please set it in this dictionary.
# you can find the supported languages list of DeepL API here: https://www.deepl.com/docs-api/translating-text/request/
# ex: DEEPL_LANGUAGES = {"fr": "FR", "en": "EN-GB", "zh_Hans": "ZH"}
'DEEPL_LANGUAGES': ('DEEPL_LANGUAGES', {}),
}
def __init__(self):
# make sure we don't assign self._settings directly here, to avoid
# recursion in __setattr__, we delegate to the parent instead
super(RosettaSettings, self).__setattr__('_settings', {})
self.load()
def load(self):
for user_setting, (rosetta_setting, default) in self.SETTINGS.items():
self._settings[rosetta_setting] = getattr(dj_settings, user_setting, default)
def reload(self):
self.__init__()
def __getattr__(self, attr):
if attr not in self._settings:
raise AttributeError("'RosettaSettings' object has not attribute '%s'" % attr)
return self._settings[attr]
def __setattr__(self, attr, value):
if attr not in self._settings:
raise AttributeError("'RosettaSettings' object has not attribute '%s'" % attr)
self._settings[attr] = value
# This is our global settings object
settings = RosettaSettings()
# Signal handler to reload settings when needed
def reload_settings(*args, **kwargs):
val = kwargs.get('setting')
if val in settings.SETTINGS:
settings.reload()
# Connect the setting_changed signal to our handler
setting_changed.connect(reload_settings)
| mit | 80845d95033b7808a07574747800940e | 40.733333 | 129 | 0.63099 | 3.536723 | false | false | false | false |
more-itertools/more-itertools | more_itertools/more.py | 1 | 133390 | import warnings
from collections import Counter, defaultdict, deque, abc
from collections.abc import Sequence
from functools import partial, reduce, wraps
from heapq import heapify, heapreplace, heappop
from itertools import (
chain,
compress,
count,
cycle,
dropwhile,
groupby,
islice,
repeat,
starmap,
takewhile,
tee,
zip_longest,
)
from math import exp, factorial, floor, log
from queue import Empty, Queue
from random import random, randrange, uniform
from operator import itemgetter, mul, sub, gt, lt, ge, le
from sys import hexversion, maxsize
from time import monotonic
from .recipes import (
_marker,
_zip_equal,
UnequalIterablesError,
consume,
flatten,
pairwise,
powerset,
take,
unique_everseen,
all_equal,
)
__all__ = [
'AbortThread',
'SequenceView',
'UnequalIterablesError',
'adjacent',
'all_unique',
'always_iterable',
'always_reversible',
'bucket',
'callback_iter',
'chunked',
'chunked_even',
'circular_shifts',
'collapse',
'combination_index',
'consecutive_groups',
'constrained_batches',
'consumer',
'count_cycle',
'countable',
'difference',
'distinct_combinations',
'distinct_permutations',
'distribute',
'divide',
'duplicates_everseen',
'duplicates_justseen',
'exactly_n',
'filter_except',
'first',
'groupby_transform',
'ichunked',
'iequals',
'ilen',
'interleave',
'interleave_evenly',
'interleave_longest',
'intersperse',
'is_sorted',
'islice_extended',
'iterate',
'last',
'locate',
'longest_common_prefix',
'lstrip',
'make_decorator',
'map_except',
'map_if',
'map_reduce',
'mark_ends',
'minmax',
'nth_or_last',
'nth_permutation',
'nth_product',
'numeric_range',
'one',
'only',
'padded',
'partitions',
'peekable',
'permutation_index',
'product_index',
'raise_',
'repeat_each',
'repeat_last',
'replace',
'rlocate',
'rstrip',
'run_length',
'sample',
'seekable',
'set_partitions',
'side_effect',
'sliced',
'sort_together',
'split_after',
'split_at',
'split_before',
'split_into',
'split_when',
'spy',
'stagger',
'strip',
'strictly_n',
'substrings',
'substrings_indexes',
'time_limited',
'unique_in_window',
'unique_to_each',
'unzip',
'value_chain',
'windowed',
'windowed_complete',
'with_iter',
'zip_broadcast',
'zip_equal',
'zip_offset',
]
def chunked(iterable, n, strict=False):
"""Break *iterable* into lists of length *n*:
>>> list(chunked([1, 2, 3, 4, 5, 6], 3))
[[1, 2, 3], [4, 5, 6]]
By the default, the last yielded list will have fewer than *n* elements
if the length of *iterable* is not divisible by *n*:
>>> list(chunked([1, 2, 3, 4, 5, 6, 7, 8], 3))
[[1, 2, 3], [4, 5, 6], [7, 8]]
To use a fill-in value instead, see the :func:`grouper` recipe.
If the length of *iterable* is not divisible by *n* and *strict* is
``True``, then ``ValueError`` will be raised before the last
list is yielded.
"""
iterator = iter(partial(take, n, iter(iterable)), [])
if strict:
if n is None:
raise ValueError('n must not be None when using strict mode.')
def ret():
for chunk in iterator:
if len(chunk) != n:
raise ValueError('iterable is not divisible by n.')
yield chunk
return iter(ret())
else:
return iterator
def first(iterable, default=_marker):
"""Return the first item of *iterable*, or *default* if *iterable* is
empty.
>>> first([0, 1, 2, 3])
0
>>> first([], 'some default')
'some default'
If *default* is not provided and there are no items in the iterable,
raise ``ValueError``.
:func:`first` is useful when you have a generator of expensive-to-retrieve
values and want any arbitrary one. It is marginally shorter than
``next(iter(iterable), default)``.
"""
try:
return next(iter(iterable))
except StopIteration as e:
if default is _marker:
raise ValueError(
'first() was called on an empty iterable, and no '
'default value was provided.'
) from e
return default
def last(iterable, default=_marker):
"""Return the last item of *iterable*, or *default* if *iterable* is
empty.
>>> last([0, 1, 2, 3])
3
>>> last([], 'some default')
'some default'
If *default* is not provided and there are no items in the iterable,
raise ``ValueError``.
"""
try:
if isinstance(iterable, Sequence):
return iterable[-1]
# Work around https://bugs.python.org/issue38525
elif hasattr(iterable, '__reversed__') and (hexversion != 0x030800F0):
return next(reversed(iterable))
else:
return deque(iterable, maxlen=1)[-1]
except (IndexError, TypeError, StopIteration):
if default is _marker:
raise ValueError(
'last() was called on an empty iterable, and no default was '
'provided.'
)
return default
def nth_or_last(iterable, n, default=_marker):
"""Return the nth or the last item of *iterable*,
or *default* if *iterable* is empty.
>>> nth_or_last([0, 1, 2, 3], 2)
2
>>> nth_or_last([0, 1], 2)
1
>>> nth_or_last([], 0, 'some default')
'some default'
If *default* is not provided and there are no items in the iterable,
raise ``ValueError``.
"""
return last(islice(iterable, n + 1), default=default)
class peekable:
"""Wrap an iterator to allow lookahead and prepending elements.
Call :meth:`peek` on the result to get the value that will be returned
by :func:`next`. This won't advance the iterator:
>>> p = peekable(['a', 'b'])
>>> p.peek()
'a'
>>> next(p)
'a'
Pass :meth:`peek` a default value to return that instead of raising
``StopIteration`` when the iterator is exhausted.
>>> p = peekable([])
>>> p.peek('hi')
'hi'
peekables also offer a :meth:`prepend` method, which "inserts" items
at the head of the iterable:
>>> p = peekable([1, 2, 3])
>>> p.prepend(10, 11, 12)
>>> next(p)
10
>>> p.peek()
11
>>> list(p)
[11, 12, 1, 2, 3]
peekables can be indexed. Index 0 is the item that will be returned by
:func:`next`, index 1 is the item after that, and so on:
The values up to the given index will be cached.
>>> p = peekable(['a', 'b', 'c', 'd'])
>>> p[0]
'a'
>>> p[1]
'b'
>>> next(p)
'a'
Negative indexes are supported, but be aware that they will cache the
remaining items in the source iterator, which may require significant
storage.
To check whether a peekable is exhausted, check its truth value:
>>> p = peekable(['a', 'b'])
>>> if p: # peekable has items
... list(p)
['a', 'b']
>>> if not p: # peekable is exhausted
... list(p)
[]
"""
def __init__(self, iterable):
self._it = iter(iterable)
self._cache = deque()
def __iter__(self):
return self
def __bool__(self):
try:
self.peek()
except StopIteration:
return False
return True
def peek(self, default=_marker):
"""Return the item that will be next returned from ``next()``.
Return ``default`` if there are no items left. If ``default`` is not
provided, raise ``StopIteration``.
"""
if not self._cache:
try:
self._cache.append(next(self._it))
except StopIteration:
if default is _marker:
raise
return default
return self._cache[0]
def prepend(self, *items):
"""Stack up items to be the next ones returned from ``next()`` or
``self.peek()``. The items will be returned in
first in, first out order::
>>> p = peekable([1, 2, 3])
>>> p.prepend(10, 11, 12)
>>> next(p)
10
>>> list(p)
[11, 12, 1, 2, 3]
It is possible, by prepending items, to "resurrect" a peekable that
previously raised ``StopIteration``.
>>> p = peekable([])
>>> next(p)
Traceback (most recent call last):
...
StopIteration
>>> p.prepend(1)
>>> next(p)
1
>>> next(p)
Traceback (most recent call last):
...
StopIteration
"""
self._cache.extendleft(reversed(items))
def __next__(self):
if self._cache:
return self._cache.popleft()
return next(self._it)
def _get_slice(self, index):
# Normalize the slice's arguments
step = 1 if (index.step is None) else index.step
if step > 0:
start = 0 if (index.start is None) else index.start
stop = maxsize if (index.stop is None) else index.stop
elif step < 0:
start = -1 if (index.start is None) else index.start
stop = (-maxsize - 1) if (index.stop is None) else index.stop
else:
raise ValueError('slice step cannot be zero')
# If either the start or stop index is negative, we'll need to cache
# the rest of the iterable in order to slice from the right side.
if (start < 0) or (stop < 0):
self._cache.extend(self._it)
# Otherwise we'll need to find the rightmost index and cache to that
# point.
else:
n = min(max(start, stop) + 1, maxsize)
cache_len = len(self._cache)
if n >= cache_len:
self._cache.extend(islice(self._it, n - cache_len))
return list(self._cache)[index]
def __getitem__(self, index):
if isinstance(index, slice):
return self._get_slice(index)
cache_len = len(self._cache)
if index < 0:
self._cache.extend(self._it)
elif index >= cache_len:
self._cache.extend(islice(self._it, index + 1 - cache_len))
return self._cache[index]
def consumer(func):
"""Decorator that automatically advances a PEP-342-style "reverse iterator"
to its first yield point so you don't have to call ``next()`` on it
manually.
>>> @consumer
... def tally():
... i = 0
... while True:
... print('Thing number %s is %s.' % (i, (yield)))
... i += 1
...
>>> t = tally()
>>> t.send('red')
Thing number 0 is red.
>>> t.send('fish')
Thing number 1 is fish.
Without the decorator, you would have to call ``next(t)`` before
``t.send()`` could be used.
"""
@wraps(func)
def wrapper(*args, **kwargs):
gen = func(*args, **kwargs)
next(gen)
return gen
return wrapper
def ilen(iterable):
"""Return the number of items in *iterable*.
>>> ilen(x for x in range(1000000) if x % 3 == 0)
333334
This consumes the iterable, so handle with care.
"""
# This approach was selected because benchmarks showed it's likely the
# fastest of the known implementations at the time of writing.
# See GitHub tracker: #236, #230.
counter = count()
deque(zip(iterable, counter), maxlen=0)
return next(counter)
def iterate(func, start):
"""Return ``start``, ``func(start)``, ``func(func(start))``, ...
>>> from itertools import islice
>>> list(islice(iterate(lambda x: 2*x, 1), 10))
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
"""
while True:
yield start
start = func(start)
def with_iter(context_manager):
"""Wrap an iterable in a ``with`` statement, so it closes once exhausted.
For example, this will close the file when the iterator is exhausted::
upper_lines = (line.upper() for line in with_iter(open('foo')))
Any context manager which returns an iterable is a candidate for
``with_iter``.
"""
with context_manager as iterable:
yield from iterable
def one(iterable, too_short=None, too_long=None):
"""Return the first item from *iterable*, which is expected to contain only
that item. Raise an exception if *iterable* is empty or has more than one
item.
:func:`one` is useful for ensuring that an iterable contains only one item.
For example, it can be used to retrieve the result of a database query
that is expected to return a single row.
If *iterable* is empty, ``ValueError`` will be raised. You may specify a
different exception with the *too_short* keyword:
>>> it = []
>>> one(it) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValueError: too many items in iterable (expected 1)'
>>> too_short = IndexError('too few items')
>>> one(it, too_short=too_short) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
IndexError: too few items
Similarly, if *iterable* contains more than one item, ``ValueError`` will
be raised. You may specify a different exception with the *too_long*
keyword:
>>> it = ['too', 'many']
>>> one(it) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValueError: Expected exactly one item in iterable, but got 'too',
'many', and perhaps more.
>>> too_long = RuntimeError
>>> one(it, too_long=too_long) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
RuntimeError
Note that :func:`one` attempts to advance *iterable* twice to ensure there
is only one item. See :func:`spy` or :func:`peekable` to check iterable
contents less destructively.
"""
it = iter(iterable)
try:
first_value = next(it)
except StopIteration as e:
raise (
too_short or ValueError('too few items in iterable (expected 1)')
) from e
try:
second_value = next(it)
except StopIteration:
pass
else:
msg = (
'Expected exactly one item in iterable, but got {!r}, {!r}, '
'and perhaps more.'.format(first_value, second_value)
)
raise too_long or ValueError(msg)
return first_value
def raise_(exception, *args):
raise exception(*args)
def strictly_n(iterable, n, too_short=None, too_long=None):
"""Validate that *iterable* has exactly *n* items and return them if
it does. If it has fewer than *n* items, call function *too_short*
with those items. If it has more than *n* items, call function
*too_long* with the first ``n + 1`` items.
>>> iterable = ['a', 'b', 'c', 'd']
>>> n = 4
>>> list(strictly_n(iterable, n))
['a', 'b', 'c', 'd']
By default, *too_short* and *too_long* are functions that raise
``ValueError``.
>>> list(strictly_n('ab', 3)) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValueError: too few items in iterable (got 2)
>>> list(strictly_n('abc', 2)) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValueError: too many items in iterable (got at least 3)
You can instead supply functions that do something else.
*too_short* will be called with the number of items in *iterable*.
*too_long* will be called with `n + 1`.
>>> def too_short(item_count):
... raise RuntimeError
>>> it = strictly_n('abcd', 6, too_short=too_short)
>>> list(it) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
RuntimeError
>>> def too_long(item_count):
... print('The boss is going to hear about this')
>>> it = strictly_n('abcdef', 4, too_long=too_long)
>>> list(it)
The boss is going to hear about this
['a', 'b', 'c', 'd']
"""
if too_short is None:
too_short = lambda item_count: raise_(
ValueError,
'Too few items in iterable (got {})'.format(item_count),
)
if too_long is None:
too_long = lambda item_count: raise_(
ValueError,
'Too many items in iterable (got at least {})'.format(item_count),
)
it = iter(iterable)
for i in range(n):
try:
item = next(it)
except StopIteration:
too_short(i)
return
else:
yield item
try:
next(it)
except StopIteration:
pass
else:
too_long(n + 1)
def distinct_permutations(iterable, r=None):
"""Yield successive distinct permutations of the elements in *iterable*.
>>> sorted(distinct_permutations([1, 0, 1]))
[(0, 1, 1), (1, 0, 1), (1, 1, 0)]
Equivalent to ``set(permutations(iterable))``, except duplicates are not
generated and thrown away. For larger input sequences this is much more
efficient.
Duplicate permutations arise when there are duplicated elements in the
input iterable. The number of items returned is
`n! / (x_1! * x_2! * ... * x_n!)`, where `n` is the total number of
items input, and each `x_i` is the count of a distinct item in the input
sequence.
If *r* is given, only the *r*-length permutations are yielded.
>>> sorted(distinct_permutations([1, 0, 1], r=2))
[(0, 1), (1, 0), (1, 1)]
>>> sorted(distinct_permutations(range(3), r=2))
[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
"""
# Algorithm: https://w.wiki/Qai
def _full(A):
while True:
# Yield the permutation we have
yield tuple(A)
# Find the largest index i such that A[i] < A[i + 1]
for i in range(size - 2, -1, -1):
if A[i] < A[i + 1]:
break
# If no such index exists, this permutation is the last one
else:
return
# Find the largest index j greater than j such that A[i] < A[j]
for j in range(size - 1, i, -1):
if A[i] < A[j]:
break
# Swap the value of A[i] with that of A[j], then reverse the
# sequence from A[i + 1] to form the new permutation
A[i], A[j] = A[j], A[i]
A[i + 1 :] = A[: i - size : -1] # A[i + 1:][::-1]
# Algorithm: modified from the above
def _partial(A, r):
# Split A into the first r items and the last r items
head, tail = A[:r], A[r:]
right_head_indexes = range(r - 1, -1, -1)
left_tail_indexes = range(len(tail))
while True:
# Yield the permutation we have
yield tuple(head)
# Starting from the right, find the first index of the head with
# value smaller than the maximum value of the tail - call it i.
pivot = tail[-1]
for i in right_head_indexes:
if head[i] < pivot:
break
pivot = head[i]
else:
return
# Starting from the left, find the first value of the tail
# with a value greater than head[i] and swap.
for j in left_tail_indexes:
if tail[j] > head[i]:
head[i], tail[j] = tail[j], head[i]
break
# If we didn't find one, start from the right and find the first
# index of the head with a value greater than head[i] and swap.
else:
for j in right_head_indexes:
if head[j] > head[i]:
head[i], head[j] = head[j], head[i]
break
# Reverse head[i + 1:] and swap it with tail[:r - (i + 1)]
tail += head[: i - r : -1] # head[i + 1:][::-1]
i += 1
head[i:], tail[:] = tail[: r - i], tail[r - i :]
items = sorted(iterable)
size = len(items)
if r is None:
r = size
if 0 < r <= size:
return _full(items) if (r == size) else _partial(items, r)
return iter(() if r else ((),))
def intersperse(e, iterable, n=1):
"""Intersperse filler element *e* among the items in *iterable*, leaving
*n* items between each filler element.
>>> list(intersperse('!', [1, 2, 3, 4, 5]))
[1, '!', 2, '!', 3, '!', 4, '!', 5]
>>> list(intersperse(None, [1, 2, 3, 4, 5], n=2))
[1, 2, None, 3, 4, None, 5]
"""
if n == 0:
raise ValueError('n must be > 0')
elif n == 1:
# interleave(repeat(e), iterable) -> e, x_0, e, x_1, e, x_2...
# islice(..., 1, None) -> x_0, e, x_1, e, x_2...
return islice(interleave(repeat(e), iterable), 1, None)
else:
# interleave(filler, chunks) -> [e], [x_0, x_1], [e], [x_2, x_3]...
# islice(..., 1, None) -> [x_0, x_1], [e], [x_2, x_3]...
# flatten(...) -> x_0, x_1, e, x_2, x_3...
filler = repeat([e])
chunks = chunked(iterable, n)
return flatten(islice(interleave(filler, chunks), 1, None))
def unique_to_each(*iterables):
"""Return the elements from each of the input iterables that aren't in the
other input iterables.
For example, suppose you have a set of packages, each with a set of
dependencies::
{'pkg_1': {'A', 'B'}, 'pkg_2': {'B', 'C'}, 'pkg_3': {'B', 'D'}}
If you remove one package, which dependencies can also be removed?
If ``pkg_1`` is removed, then ``A`` is no longer necessary - it is not
associated with ``pkg_2`` or ``pkg_3``. Similarly, ``C`` is only needed for
``pkg_2``, and ``D`` is only needed for ``pkg_3``::
>>> unique_to_each({'A', 'B'}, {'B', 'C'}, {'B', 'D'})
[['A'], ['C'], ['D']]
If there are duplicates in one input iterable that aren't in the others
they will be duplicated in the output. Input order is preserved::
>>> unique_to_each("mississippi", "missouri")
[['p', 'p'], ['o', 'u', 'r']]
It is assumed that the elements of each iterable are hashable.
"""
pool = [list(it) for it in iterables]
counts = Counter(chain.from_iterable(map(set, pool)))
uniques = {element for element in counts if counts[element] == 1}
return [list(filter(uniques.__contains__, it)) for it in pool]
def windowed(seq, n, fillvalue=None, step=1):
"""Return a sliding window of width *n* over the given iterable.
>>> all_windows = windowed([1, 2, 3, 4, 5], 3)
>>> list(all_windows)
[(1, 2, 3), (2, 3, 4), (3, 4, 5)]
When the window is larger than the iterable, *fillvalue* is used in place
of missing values:
>>> list(windowed([1, 2, 3], 4))
[(1, 2, 3, None)]
Each window will advance in increments of *step*:
>>> list(windowed([1, 2, 3, 4, 5, 6], 3, fillvalue='!', step=2))
[(1, 2, 3), (3, 4, 5), (5, 6, '!')]
To slide into the iterable's items, use :func:`chain` to add filler items
to the left:
>>> iterable = [1, 2, 3, 4]
>>> n = 3
>>> padding = [None] * (n - 1)
>>> list(windowed(chain(padding, iterable), 3))
[(None, None, 1), (None, 1, 2), (1, 2, 3), (2, 3, 4)]
"""
if n < 0:
raise ValueError('n must be >= 0')
if n == 0:
yield tuple()
return
if step < 1:
raise ValueError('step must be >= 1')
window = deque(maxlen=n)
i = n
for _ in map(window.append, seq):
i -= 1
if not i:
i = step
yield tuple(window)
size = len(window)
if size == 0:
return
elif size < n:
yield tuple(chain(window, repeat(fillvalue, n - size)))
elif 0 < i < min(step, n):
window += (fillvalue,) * i
yield tuple(window)
def substrings(iterable):
"""Yield all of the substrings of *iterable*.
>>> [''.join(s) for s in substrings('more')]
['m', 'o', 'r', 'e', 'mo', 'or', 're', 'mor', 'ore', 'more']
Note that non-string iterables can also be subdivided.
>>> list(substrings([0, 1, 2]))
[(0,), (1,), (2,), (0, 1), (1, 2), (0, 1, 2)]
"""
# The length-1 substrings
seq = []
for item in iter(iterable):
seq.append(item)
yield (item,)
seq = tuple(seq)
item_count = len(seq)
# And the rest
for n in range(2, item_count + 1):
for i in range(item_count - n + 1):
yield seq[i : i + n]
def substrings_indexes(seq, reverse=False):
"""Yield all substrings and their positions in *seq*
The items yielded will be a tuple of the form ``(substr, i, j)``, where
``substr == seq[i:j]``.
This function only works for iterables that support slicing, such as
``str`` objects.
>>> for item in substrings_indexes('more'):
... print(item)
('m', 0, 1)
('o', 1, 2)
('r', 2, 3)
('e', 3, 4)
('mo', 0, 2)
('or', 1, 3)
('re', 2, 4)
('mor', 0, 3)
('ore', 1, 4)
('more', 0, 4)
Set *reverse* to ``True`` to yield the same items in the opposite order.
"""
r = range(1, len(seq) + 1)
if reverse:
r = reversed(r)
return (
(seq[i : i + L], i, i + L) for L in r for i in range(len(seq) - L + 1)
)
class bucket:
"""Wrap *iterable* and return an object that buckets it iterable into
child iterables based on a *key* function.
>>> iterable = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'b3']
>>> s = bucket(iterable, key=lambda x: x[0]) # Bucket by 1st character
>>> sorted(list(s)) # Get the keys
['a', 'b', 'c']
>>> a_iterable = s['a']
>>> next(a_iterable)
'a1'
>>> next(a_iterable)
'a2'
>>> list(s['b'])
['b1', 'b2', 'b3']
The original iterable will be advanced and its items will be cached until
they are used by the child iterables. This may require significant storage.
By default, attempting to select a bucket to which no items belong will
exhaust the iterable and cache all values.
If you specify a *validator* function, selected buckets will instead be
checked against it.
>>> from itertools import count
>>> it = count(1, 2) # Infinite sequence of odd numbers
>>> key = lambda x: x % 10 # Bucket by last digit
>>> validator = lambda x: x in {1, 3, 5, 7, 9} # Odd digits only
>>> s = bucket(it, key=key, validator=validator)
>>> 2 in s
False
>>> list(s[2])
[]
"""
def __init__(self, iterable, key, validator=None):
self._it = iter(iterable)
self._key = key
self._cache = defaultdict(deque)
self._validator = validator or (lambda x: True)
def __contains__(self, value):
if not self._validator(value):
return False
try:
item = next(self[value])
except StopIteration:
return False
else:
self._cache[value].appendleft(item)
return True
def _get_values(self, value):
"""
Helper to yield items from the parent iterator that match *value*.
Items that don't match are stored in the local cache as they
are encountered.
"""
while True:
# If we've cached some items that match the target value, emit
# the first one and evict it from the cache.
if self._cache[value]:
yield self._cache[value].popleft()
# Otherwise we need to advance the parent iterator to search for
# a matching item, caching the rest.
else:
while True:
try:
item = next(self._it)
except StopIteration:
return
item_value = self._key(item)
if item_value == value:
yield item
break
elif self._validator(item_value):
self._cache[item_value].append(item)
def __iter__(self):
for item in self._it:
item_value = self._key(item)
if self._validator(item_value):
self._cache[item_value].append(item)
yield from self._cache.keys()
def __getitem__(self, value):
if not self._validator(value):
return iter(())
return self._get_values(value)
def spy(iterable, n=1):
"""Return a 2-tuple with a list containing the first *n* elements of
*iterable*, and an iterator with the same items as *iterable*.
This allows you to "look ahead" at the items in the iterable without
advancing it.
There is one item in the list by default:
>>> iterable = 'abcdefg'
>>> head, iterable = spy(iterable)
>>> head
['a']
>>> list(iterable)
['a', 'b', 'c', 'd', 'e', 'f', 'g']
You may use unpacking to retrieve items instead of lists:
>>> (head,), iterable = spy('abcdefg')
>>> head
'a'
>>> (first, second), iterable = spy('abcdefg', 2)
>>> first
'a'
>>> second
'b'
The number of items requested can be larger than the number of items in
the iterable:
>>> iterable = [1, 2, 3, 4, 5]
>>> head, iterable = spy(iterable, 10)
>>> head
[1, 2, 3, 4, 5]
>>> list(iterable)
[1, 2, 3, 4, 5]
"""
it = iter(iterable)
head = take(n, it)
return head.copy(), chain(head, it)
def interleave(*iterables):
"""Return a new iterable yielding from each iterable in turn,
until the shortest is exhausted.
>>> list(interleave([1, 2, 3], [4, 5], [6, 7, 8]))
[1, 4, 6, 2, 5, 7]
For a version that doesn't terminate after the shortest iterable is
exhausted, see :func:`interleave_longest`.
"""
return chain.from_iterable(zip(*iterables))
def interleave_longest(*iterables):
"""Return a new iterable yielding from each iterable in turn,
skipping any that are exhausted.
>>> list(interleave_longest([1, 2, 3], [4, 5], [6, 7, 8]))
[1, 4, 6, 2, 5, 7, 3, 8]
This function produces the same output as :func:`roundrobin`, but may
perform better for some inputs (in particular when the number of iterables
is large).
"""
i = chain.from_iterable(zip_longest(*iterables, fillvalue=_marker))
return (x for x in i if x is not _marker)
def interleave_evenly(iterables, lengths=None):
"""
Interleave multiple iterables so that their elements are evenly distributed
throughout the output sequence.
>>> iterables = [1, 2, 3, 4, 5], ['a', 'b']
>>> list(interleave_evenly(iterables))
[1, 2, 'a', 3, 4, 'b', 5]
>>> iterables = [[1, 2, 3], [4, 5], [6, 7, 8]]
>>> list(interleave_evenly(iterables))
[1, 6, 4, 2, 7, 3, 8, 5]
This function requires iterables of known length. Iterables without
``__len__()`` can be used by manually specifying lengths with *lengths*:
>>> from itertools import combinations, repeat
>>> iterables = [combinations(range(4), 2), ['a', 'b', 'c']]
>>> lengths = [4 * (4 - 1) // 2, 3]
>>> list(interleave_evenly(iterables, lengths=lengths))
[(0, 1), (0, 2), 'a', (0, 3), (1, 2), 'b', (1, 3), (2, 3), 'c']
Based on Bresenham's algorithm.
"""
if lengths is None:
try:
lengths = [len(it) for it in iterables]
except TypeError:
raise ValueError(
'Iterable lengths could not be determined automatically. '
'Specify them with the lengths keyword.'
)
elif len(iterables) != len(lengths):
raise ValueError('Mismatching number of iterables and lengths.')
dims = len(lengths)
# sort iterables by length, descending
lengths_permute = sorted(
range(dims), key=lambda i: lengths[i], reverse=True
)
lengths_desc = [lengths[i] for i in lengths_permute]
iters_desc = [iter(iterables[i]) for i in lengths_permute]
# the longest iterable is the primary one (Bresenham: the longest
# distance along an axis)
delta_primary, deltas_secondary = lengths_desc[0], lengths_desc[1:]
iter_primary, iters_secondary = iters_desc[0], iters_desc[1:]
errors = [delta_primary // dims] * len(deltas_secondary)
to_yield = sum(lengths)
while to_yield:
yield next(iter_primary)
to_yield -= 1
# update errors for each secondary iterable
errors = [e - delta for e, delta in zip(errors, deltas_secondary)]
# those iterables for which the error is negative are yielded
# ("diagonal step" in Bresenham)
for i, e in enumerate(errors):
if e < 0:
yield next(iters_secondary[i])
to_yield -= 1
errors[i] += delta_primary
def collapse(iterable, base_type=None, levels=None):
"""Flatten an iterable with multiple levels of nesting (e.g., a list of
lists of tuples) into non-iterable types.
>>> iterable = [(1, 2), ([3, 4], [[5], [6]])]
>>> list(collapse(iterable))
[1, 2, 3, 4, 5, 6]
Binary and text strings are not considered iterable and
will not be collapsed.
To avoid collapsing other types, specify *base_type*:
>>> iterable = ['ab', ('cd', 'ef'), ['gh', 'ij']]
>>> list(collapse(iterable, base_type=tuple))
['ab', ('cd', 'ef'), 'gh', 'ij']
Specify *levels* to stop flattening after a certain level:
>>> iterable = [('a', ['b']), ('c', ['d'])]
>>> list(collapse(iterable)) # Fully flattened
['a', 'b', 'c', 'd']
>>> list(collapse(iterable, levels=1)) # Only one level flattened
['a', ['b'], 'c', ['d']]
"""
def walk(node, level):
if (
((levels is not None) and (level > levels))
or isinstance(node, (str, bytes))
or ((base_type is not None) and isinstance(node, base_type))
):
yield node
return
try:
tree = iter(node)
except TypeError:
yield node
return
else:
for child in tree:
yield from walk(child, level + 1)
yield from walk(iterable, 0)
def side_effect(func, iterable, chunk_size=None, before=None, after=None):
"""Invoke *func* on each item in *iterable* (or on each *chunk_size* group
of items) before yielding the item.
`func` must be a function that takes a single argument. Its return value
will be discarded.
*before* and *after* are optional functions that take no arguments. They
will be executed before iteration starts and after it ends, respectively.
`side_effect` can be used for logging, updating progress bars, or anything
that is not functionally "pure."
Emitting a status message:
>>> from more_itertools import consume
>>> func = lambda item: print('Received {}'.format(item))
>>> consume(side_effect(func, range(2)))
Received 0
Received 1
Operating on chunks of items:
>>> pair_sums = []
>>> func = lambda chunk: pair_sums.append(sum(chunk))
>>> list(side_effect(func, [0, 1, 2, 3, 4, 5], 2))
[0, 1, 2, 3, 4, 5]
>>> list(pair_sums)
[1, 5, 9]
Writing to a file-like object:
>>> from io import StringIO
>>> from more_itertools import consume
>>> f = StringIO()
>>> func = lambda x: print(x, file=f)
>>> before = lambda: print(u'HEADER', file=f)
>>> after = f.close
>>> it = [u'a', u'b', u'c']
>>> consume(side_effect(func, it, before=before, after=after))
>>> f.closed
True
"""
try:
if before is not None:
before()
if chunk_size is None:
for item in iterable:
func(item)
yield item
else:
for chunk in chunked(iterable, chunk_size):
func(chunk)
yield from chunk
finally:
if after is not None:
after()
def sliced(seq, n, strict=False):
"""Yield slices of length *n* from the sequence *seq*.
>>> list(sliced((1, 2, 3, 4, 5, 6), 3))
[(1, 2, 3), (4, 5, 6)]
By the default, the last yielded slice will have fewer than *n* elements
if the length of *seq* is not divisible by *n*:
>>> list(sliced((1, 2, 3, 4, 5, 6, 7, 8), 3))
[(1, 2, 3), (4, 5, 6), (7, 8)]
If the length of *seq* is not divisible by *n* and *strict* is
``True``, then ``ValueError`` will be raised before the last
slice is yielded.
This function will only work for iterables that support slicing.
For non-sliceable iterables, see :func:`chunked`.
"""
iterator = takewhile(len, (seq[i : i + n] for i in count(0, n)))
if strict:
def ret():
for _slice in iterator:
if len(_slice) != n:
raise ValueError("seq is not divisible by n.")
yield _slice
return iter(ret())
else:
return iterator
def split_at(iterable, pred, maxsplit=-1, keep_separator=False):
"""Yield lists of items from *iterable*, where each list is delimited by
an item where callable *pred* returns ``True``.
>>> list(split_at('abcdcba', lambda x: x == 'b'))
[['a'], ['c', 'd', 'c'], ['a']]
>>> list(split_at(range(10), lambda n: n % 2 == 1))
[[0], [2], [4], [6], [8], []]
At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,
then there is no limit on the number of splits:
>>> list(split_at(range(10), lambda n: n % 2 == 1, maxsplit=2))
[[0], [2], [4, 5, 6, 7, 8, 9]]
By default, the delimiting items are not included in the output.
The include them, set *keep_separator* to ``True``.
>>> list(split_at('abcdcba', lambda x: x == 'b', keep_separator=True))
[['a'], ['b'], ['c', 'd', 'c'], ['b'], ['a']]
"""
if maxsplit == 0:
yield list(iterable)
return
buf = []
it = iter(iterable)
for item in it:
if pred(item):
yield buf
if keep_separator:
yield [item]
if maxsplit == 1:
yield list(it)
return
buf = []
maxsplit -= 1
else:
buf.append(item)
yield buf
def split_before(iterable, pred, maxsplit=-1):
"""Yield lists of items from *iterable*, where each list ends just before
an item for which callable *pred* returns ``True``:
>>> list(split_before('OneTwo', lambda s: s.isupper()))
[['O', 'n', 'e'], ['T', 'w', 'o']]
>>> list(split_before(range(10), lambda n: n % 3 == 0))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,
then there is no limit on the number of splits:
>>> list(split_before(range(10), lambda n: n % 3 == 0, maxsplit=2))
[[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]
"""
if maxsplit == 0:
yield list(iterable)
return
buf = []
it = iter(iterable)
for item in it:
if pred(item) and buf:
yield buf
if maxsplit == 1:
yield [item] + list(it)
return
buf = []
maxsplit -= 1
buf.append(item)
if buf:
yield buf
def split_after(iterable, pred, maxsplit=-1):
"""Yield lists of items from *iterable*, where each list ends with an
item where callable *pred* returns ``True``:
>>> list(split_after('one1two2', lambda s: s.isdigit()))
[['o', 'n', 'e', '1'], ['t', 'w', 'o', '2']]
>>> list(split_after(range(10), lambda n: n % 3 == 0))
[[0], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,
then there is no limit on the number of splits:
>>> list(split_after(range(10), lambda n: n % 3 == 0, maxsplit=2))
[[0], [1, 2, 3], [4, 5, 6, 7, 8, 9]]
"""
if maxsplit == 0:
yield list(iterable)
return
buf = []
it = iter(iterable)
for item in it:
buf.append(item)
if pred(item) and buf:
yield buf
if maxsplit == 1:
buf = list(it)
if buf:
yield buf
return
buf = []
maxsplit -= 1
if buf:
yield buf
def split_when(iterable, pred, maxsplit=-1):
"""Split *iterable* into pieces based on the output of *pred*.
*pred* should be a function that takes successive pairs of items and
returns ``True`` if the iterable should be split in between them.
For example, to find runs of increasing numbers, split the iterable when
element ``i`` is larger than element ``i + 1``:
>>> list(split_when([1, 2, 3, 3, 2, 5, 2, 4, 2], lambda x, y: x > y))
[[1, 2, 3, 3], [2, 5], [2, 4], [2]]
At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,
then there is no limit on the number of splits:
>>> list(split_when([1, 2, 3, 3, 2, 5, 2, 4, 2],
... lambda x, y: x > y, maxsplit=2))
[[1, 2, 3, 3], [2, 5], [2, 4, 2]]
"""
if maxsplit == 0:
yield list(iterable)
return
it = iter(iterable)
try:
cur_item = next(it)
except StopIteration:
return
buf = [cur_item]
for next_item in it:
if pred(cur_item, next_item):
yield buf
if maxsplit == 1:
yield [next_item] + list(it)
return
buf = []
maxsplit -= 1
buf.append(next_item)
cur_item = next_item
yield buf
def split_into(iterable, sizes):
"""Yield a list of sequential items from *iterable* of length 'n' for each
integer 'n' in *sizes*.
>>> list(split_into([1,2,3,4,5,6], [1,2,3]))
[[1], [2, 3], [4, 5, 6]]
If the sum of *sizes* is smaller than the length of *iterable*, then the
remaining items of *iterable* will not be returned.
>>> list(split_into([1,2,3,4,5,6], [2,3]))
[[1, 2], [3, 4, 5]]
If the sum of *sizes* is larger than the length of *iterable*, fewer items
will be returned in the iteration that overruns *iterable* and further
lists will be empty:
>>> list(split_into([1,2,3,4], [1,2,3,4]))
[[1], [2, 3], [4], []]
When a ``None`` object is encountered in *sizes*, the returned list will
contain items up to the end of *iterable* the same way that itertools.slice
does:
>>> list(split_into([1,2,3,4,5,6,7,8,9,0], [2,3,None]))
[[1, 2], [3, 4, 5], [6, 7, 8, 9, 0]]
:func:`split_into` can be useful for grouping a series of items where the
sizes of the groups are not uniform. An example would be where in a row
from a table, multiple columns represent elements of the same feature
(e.g. a point represented by x,y,z) but, the format is not the same for
all columns.
"""
# convert the iterable argument into an iterator so its contents can
# be consumed by islice in case it is a generator
it = iter(iterable)
for size in sizes:
if size is None:
yield list(it)
return
else:
yield list(islice(it, size))
def padded(iterable, fillvalue=None, n=None, next_multiple=False):
"""Yield the elements from *iterable*, followed by *fillvalue*, such that
at least *n* items are emitted.
>>> list(padded([1, 2, 3], '?', 5))
[1, 2, 3, '?', '?']
If *next_multiple* is ``True``, *fillvalue* will be emitted until the
number of items emitted is a multiple of *n*::
>>> list(padded([1, 2, 3, 4], n=3, next_multiple=True))
[1, 2, 3, 4, None, None]
If *n* is ``None``, *fillvalue* will be emitted indefinitely.
"""
it = iter(iterable)
if n is None:
yield from chain(it, repeat(fillvalue))
elif n < 1:
raise ValueError('n must be at least 1')
else:
item_count = 0
for item in it:
yield item
item_count += 1
remaining = (n - item_count) % n if next_multiple else n - item_count
for _ in range(remaining):
yield fillvalue
def repeat_each(iterable, n=2):
"""Repeat each element in *iterable* *n* times.
>>> list(repeat_each('ABC', 3))
['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']
"""
return chain.from_iterable(map(repeat, iterable, repeat(n)))
def repeat_last(iterable, default=None):
"""After the *iterable* is exhausted, keep yielding its last element.
>>> list(islice(repeat_last(range(3)), 5))
[0, 1, 2, 2, 2]
If the iterable is empty, yield *default* forever::
>>> list(islice(repeat_last(range(0), 42), 5))
[42, 42, 42, 42, 42]
"""
item = _marker
for item in iterable:
yield item
final = default if item is _marker else item
yield from repeat(final)
def distribute(n, iterable):
"""Distribute the items from *iterable* among *n* smaller iterables.
>>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6])
>>> list(group_1)
[1, 3, 5]
>>> list(group_2)
[2, 4, 6]
If the length of *iterable* is not evenly divisible by *n*, then the
length of the returned iterables will not be identical:
>>> children = distribute(3, [1, 2, 3, 4, 5, 6, 7])
>>> [list(c) for c in children]
[[1, 4, 7], [2, 5], [3, 6]]
If the length of *iterable* is smaller than *n*, then the last returned
iterables will be empty:
>>> children = distribute(5, [1, 2, 3])
>>> [list(c) for c in children]
[[1], [2], [3], [], []]
This function uses :func:`itertools.tee` and may require significant
storage. If you need the order items in the smaller iterables to match the
original iterable, see :func:`divide`.
"""
if n < 1:
raise ValueError('n must be at least 1')
children = tee(iterable, n)
return [islice(it, index, None, n) for index, it in enumerate(children)]
def stagger(iterable, offsets=(-1, 0, 1), longest=False, fillvalue=None):
"""Yield tuples whose elements are offset from *iterable*.
The amount by which the `i`-th item in each tuple is offset is given by
the `i`-th item in *offsets*.
>>> list(stagger([0, 1, 2, 3]))
[(None, 0, 1), (0, 1, 2), (1, 2, 3)]
>>> list(stagger(range(8), offsets=(0, 2, 4)))
[(0, 2, 4), (1, 3, 5), (2, 4, 6), (3, 5, 7)]
By default, the sequence will end when the final element of a tuple is the
last item in the iterable. To continue until the first element of a tuple
is the last item in the iterable, set *longest* to ``True``::
>>> list(stagger([0, 1, 2, 3], longest=True))
[(None, 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, None), (3, None, None)]
By default, ``None`` will be used to replace offsets beyond the end of the
sequence. Specify *fillvalue* to use some other value.
"""
children = tee(iterable, len(offsets))
return zip_offset(
*children, offsets=offsets, longest=longest, fillvalue=fillvalue
)
def zip_equal(*iterables):
"""``zip`` the input *iterables* together, but raise
``UnequalIterablesError`` if they aren't all the same length.
>>> it_1 = range(3)
>>> it_2 = iter('abc')
>>> list(zip_equal(it_1, it_2))
[(0, 'a'), (1, 'b'), (2, 'c')]
>>> it_1 = range(3)
>>> it_2 = iter('abcd')
>>> list(zip_equal(it_1, it_2)) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
more_itertools.more.UnequalIterablesError: Iterables have different
lengths
"""
if hexversion >= 0x30A00A6:
warnings.warn(
(
'zip_equal will be removed in a future version of '
'more-itertools. Use the builtin zip function with '
'strict=True instead.'
),
DeprecationWarning,
)
return _zip_equal(*iterables)
def zip_offset(*iterables, offsets, longest=False, fillvalue=None):
"""``zip`` the input *iterables* together, but offset the `i`-th iterable
by the `i`-th item in *offsets*.
>>> list(zip_offset('0123', 'abcdef', offsets=(0, 1)))
[('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e')]
This can be used as a lightweight alternative to SciPy or pandas to analyze
data sets in which some series have a lead or lag relationship.
By default, the sequence will end when the shortest iterable is exhausted.
To continue until the longest iterable is exhausted, set *longest* to
``True``.
>>> list(zip_offset('0123', 'abcdef', offsets=(0, 1), longest=True))
[('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e'), (None, 'f')]
By default, ``None`` will be used to replace offsets beyond the end of the
sequence. Specify *fillvalue* to use some other value.
"""
if len(iterables) != len(offsets):
raise ValueError("Number of iterables and offsets didn't match")
staggered = []
for it, n in zip(iterables, offsets):
if n < 0:
staggered.append(chain(repeat(fillvalue, -n), it))
elif n > 0:
staggered.append(islice(it, n, None))
else:
staggered.append(it)
if longest:
return zip_longest(*staggered, fillvalue=fillvalue)
return zip(*staggered)
def sort_together(iterables, key_list=(0,), key=None, reverse=False):
"""Return the input iterables sorted together, with *key_list* as the
priority for sorting. All iterables are trimmed to the length of the
shortest one.
This can be used like the sorting function in a spreadsheet. If each
iterable represents a column of data, the key list determines which
columns are used for sorting.
By default, all iterables are sorted using the ``0``-th iterable::
>>> iterables = [(4, 3, 2, 1), ('a', 'b', 'c', 'd')]
>>> sort_together(iterables)
[(1, 2, 3, 4), ('d', 'c', 'b', 'a')]
Set a different key list to sort according to another iterable.
Specifying multiple keys dictates how ties are broken::
>>> iterables = [(3, 1, 2), (0, 1, 0), ('c', 'b', 'a')]
>>> sort_together(iterables, key_list=(1, 2))
[(2, 3, 1), (0, 0, 1), ('a', 'c', 'b')]
To sort by a function of the elements of the iterable, pass a *key*
function. Its arguments are the elements of the iterables corresponding to
the key list::
>>> names = ('a', 'b', 'c')
>>> lengths = (1, 2, 3)
>>> widths = (5, 2, 1)
>>> def area(length, width):
... return length * width
>>> sort_together([names, lengths, widths], key_list=(1, 2), key=area)
[('c', 'b', 'a'), (3, 2, 1), (1, 2, 5)]
Set *reverse* to ``True`` to sort in descending order.
>>> sort_together([(1, 2, 3), ('c', 'b', 'a')], reverse=True)
[(3, 2, 1), ('a', 'b', 'c')]
"""
if key is None:
# if there is no key function, the key argument to sorted is an
# itemgetter
key_argument = itemgetter(*key_list)
else:
# if there is a key function, call it with the items at the offsets
# specified by the key function as arguments
key_list = list(key_list)
if len(key_list) == 1:
# if key_list contains a single item, pass the item at that offset
# as the only argument to the key function
key_offset = key_list[0]
key_argument = lambda zipped_items: key(zipped_items[key_offset])
else:
# if key_list contains multiple items, use itemgetter to return a
# tuple of items, which we pass as *args to the key function
get_key_items = itemgetter(*key_list)
key_argument = lambda zipped_items: key(
*get_key_items(zipped_items)
)
return list(
zip(*sorted(zip(*iterables), key=key_argument, reverse=reverse))
)
def unzip(iterable):
"""The inverse of :func:`zip`, this function disaggregates the elements
of the zipped *iterable*.
The ``i``-th iterable contains the ``i``-th element from each element
of the zipped iterable. The first element is used to determine the
length of the remaining elements.
>>> iterable = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> letters, numbers = unzip(iterable)
>>> list(letters)
['a', 'b', 'c', 'd']
>>> list(numbers)
[1, 2, 3, 4]
This is similar to using ``zip(*iterable)``, but it avoids reading
*iterable* into memory. Note, however, that this function uses
:func:`itertools.tee` and thus may require significant storage.
"""
head, iterable = spy(iter(iterable))
if not head:
# empty iterable, e.g. zip([], [], [])
return ()
# spy returns a one-length iterable as head
head = head[0]
iterables = tee(iterable, len(head))
def itemgetter(i):
def getter(obj):
try:
return obj[i]
except IndexError:
# basically if we have an iterable like
# iter([(1, 2, 3), (4, 5), (6,)])
# the second unzipped iterable would fail at the third tuple
# since it would try to access tup[1]
# same with the third unzipped iterable and the second tuple
# to support these "improperly zipped" iterables,
# we create a custom itemgetter
# which just stops the unzipped iterables
# at first length mismatch
raise StopIteration
return getter
return tuple(map(itemgetter(i), it) for i, it in enumerate(iterables))
def divide(n, iterable):
"""Divide the elements from *iterable* into *n* parts, maintaining
order.
>>> group_1, group_2 = divide(2, [1, 2, 3, 4, 5, 6])
>>> list(group_1)
[1, 2, 3]
>>> list(group_2)
[4, 5, 6]
If the length of *iterable* is not evenly divisible by *n*, then the
length of the returned iterables will not be identical:
>>> children = divide(3, [1, 2, 3, 4, 5, 6, 7])
>>> [list(c) for c in children]
[[1, 2, 3], [4, 5], [6, 7]]
If the length of the iterable is smaller than n, then the last returned
iterables will be empty:
>>> children = divide(5, [1, 2, 3])
>>> [list(c) for c in children]
[[1], [2], [3], [], []]
This function will exhaust the iterable before returning and may require
significant storage. If order is not important, see :func:`distribute`,
which does not first pull the iterable into memory.
"""
if n < 1:
raise ValueError('n must be at least 1')
try:
iterable[:0]
except TypeError:
seq = tuple(iterable)
else:
seq = iterable
q, r = divmod(len(seq), n)
ret = []
stop = 0
for i in range(1, n + 1):
start = stop
stop += q + 1 if i <= r else q
ret.append(iter(seq[start:stop]))
return ret
def always_iterable(obj, base_type=(str, bytes)):
"""If *obj* is iterable, return an iterator over its items::
>>> obj = (1, 2, 3)
>>> list(always_iterable(obj))
[1, 2, 3]
If *obj* is not iterable, return a one-item iterable containing *obj*::
>>> obj = 1
>>> list(always_iterable(obj))
[1]
If *obj* is ``None``, return an empty iterable:
>>> obj = None
>>> list(always_iterable(None))
[]
By default, binary and text strings are not considered iterable::
>>> obj = 'foo'
>>> list(always_iterable(obj))
['foo']
If *base_type* is set, objects for which ``isinstance(obj, base_type)``
returns ``True`` won't be considered iterable.
>>> obj = {'a': 1}
>>> list(always_iterable(obj)) # Iterate over the dict's keys
['a']
>>> list(always_iterable(obj, base_type=dict)) # Treat dicts as a unit
[{'a': 1}]
Set *base_type* to ``None`` to avoid any special handling and treat objects
Python considers iterable as iterable:
>>> obj = 'foo'
>>> list(always_iterable(obj, base_type=None))
['f', 'o', 'o']
"""
if obj is None:
return iter(())
if (base_type is not None) and isinstance(obj, base_type):
return iter((obj,))
try:
return iter(obj)
except TypeError:
return iter((obj,))
def adjacent(predicate, iterable, distance=1):
"""Return an iterable over `(bool, item)` tuples where the `item` is
drawn from *iterable* and the `bool` indicates whether
that item satisfies the *predicate* or is adjacent to an item that does.
For example, to find whether items are adjacent to a ``3``::
>>> list(adjacent(lambda x: x == 3, range(6)))
[(False, 0), (False, 1), (True, 2), (True, 3), (True, 4), (False, 5)]
Set *distance* to change what counts as adjacent. For example, to find
whether items are two places away from a ``3``:
>>> list(adjacent(lambda x: x == 3, range(6), distance=2))
[(False, 0), (True, 1), (True, 2), (True, 3), (True, 4), (True, 5)]
This is useful for contextualizing the results of a search function.
For example, a code comparison tool might want to identify lines that
have changed, but also surrounding lines to give the viewer of the diff
context.
The predicate function will only be called once for each item in the
iterable.
See also :func:`groupby_transform`, which can be used with this function
to group ranges of items with the same `bool` value.
"""
# Allow distance=0 mainly for testing that it reproduces results with map()
if distance < 0:
raise ValueError('distance must be at least 0')
i1, i2 = tee(iterable)
padding = [False] * distance
selected = chain(padding, map(predicate, i1), padding)
adjacent_to_selected = map(any, windowed(selected, 2 * distance + 1))
return zip(adjacent_to_selected, i2)
def groupby_transform(iterable, keyfunc=None, valuefunc=None, reducefunc=None):
"""An extension of :func:`itertools.groupby` that can apply transformations
to the grouped data.
* *keyfunc* is a function computing a key value for each item in *iterable*
* *valuefunc* is a function that transforms the individual items from
*iterable* after grouping
* *reducefunc* is a function that transforms each group of items
>>> iterable = 'aAAbBBcCC'
>>> keyfunc = lambda k: k.upper()
>>> valuefunc = lambda v: v.lower()
>>> reducefunc = lambda g: ''.join(g)
>>> list(groupby_transform(iterable, keyfunc, valuefunc, reducefunc))
[('A', 'aaa'), ('B', 'bbb'), ('C', 'ccc')]
Each optional argument defaults to an identity function if not specified.
:func:`groupby_transform` is useful when grouping elements of an iterable
using a separate iterable as the key. To do this, :func:`zip` the iterables
and pass a *keyfunc* that extracts the first element and a *valuefunc*
that extracts the second element::
>>> from operator import itemgetter
>>> keys = [0, 0, 1, 1, 1, 2, 2, 2, 3]
>>> values = 'abcdefghi'
>>> iterable = zip(keys, values)
>>> grouper = groupby_transform(iterable, itemgetter(0), itemgetter(1))
>>> [(k, ''.join(g)) for k, g in grouper]
[(0, 'ab'), (1, 'cde'), (2, 'fgh'), (3, 'i')]
Note that the order of items in the iterable is significant.
Only adjacent items are grouped together, so if you don't want any
duplicate groups, you should sort the iterable by the key function.
"""
ret = groupby(iterable, keyfunc)
if valuefunc:
ret = ((k, map(valuefunc, g)) for k, g in ret)
if reducefunc:
ret = ((k, reducefunc(g)) for k, g in ret)
return ret
class numeric_range(abc.Sequence, abc.Hashable):
"""An extension of the built-in ``range()`` function whose arguments can
be any orderable numeric type.
With only *stop* specified, *start* defaults to ``0`` and *step*
defaults to ``1``. The output items will match the type of *stop*:
>>> list(numeric_range(3.5))
[0.0, 1.0, 2.0, 3.0]
With only *start* and *stop* specified, *step* defaults to ``1``. The
output items will match the type of *start*:
>>> from decimal import Decimal
>>> start = Decimal('2.1')
>>> stop = Decimal('5.1')
>>> list(numeric_range(start, stop))
[Decimal('2.1'), Decimal('3.1'), Decimal('4.1')]
With *start*, *stop*, and *step* specified the output items will match
the type of ``start + step``:
>>> from fractions import Fraction
>>> start = Fraction(1, 2) # Start at 1/2
>>> stop = Fraction(5, 2) # End at 5/2
>>> step = Fraction(1, 2) # Count by 1/2
>>> list(numeric_range(start, stop, step))
[Fraction(1, 2), Fraction(1, 1), Fraction(3, 2), Fraction(2, 1)]
If *step* is zero, ``ValueError`` is raised. Negative steps are supported:
>>> list(numeric_range(3, -1, -1.0))
[3.0, 2.0, 1.0, 0.0]
Be aware of the limitations of floating point numbers; the representation
of the yielded numbers may be surprising.
``datetime.datetime`` objects can be used for *start* and *stop*, if *step*
is a ``datetime.timedelta`` object:
>>> import datetime
>>> start = datetime.datetime(2019, 1, 1)
>>> stop = datetime.datetime(2019, 1, 3)
>>> step = datetime.timedelta(days=1)
>>> items = iter(numeric_range(start, stop, step))
>>> next(items)
datetime.datetime(2019, 1, 1, 0, 0)
>>> next(items)
datetime.datetime(2019, 1, 2, 0, 0)
"""
_EMPTY_HASH = hash(range(0, 0))
def __init__(self, *args):
argc = len(args)
if argc == 1:
(self._stop,) = args
self._start = type(self._stop)(0)
self._step = type(self._stop - self._start)(1)
elif argc == 2:
self._start, self._stop = args
self._step = type(self._stop - self._start)(1)
elif argc == 3:
self._start, self._stop, self._step = args
elif argc == 0:
raise TypeError(
'numeric_range expected at least '
'1 argument, got {}'.format(argc)
)
else:
raise TypeError(
'numeric_range expected at most '
'3 arguments, got {}'.format(argc)
)
self._zero = type(self._step)(0)
if self._step == self._zero:
raise ValueError('numeric_range() arg 3 must not be zero')
self._growing = self._step > self._zero
self._init_len()
def __bool__(self):
if self._growing:
return self._start < self._stop
else:
return self._start > self._stop
def __contains__(self, elem):
if self._growing:
if self._start <= elem < self._stop:
return (elem - self._start) % self._step == self._zero
else:
if self._start >= elem > self._stop:
return (self._start - elem) % (-self._step) == self._zero
return False
def __eq__(self, other):
if isinstance(other, numeric_range):
empty_self = not bool(self)
empty_other = not bool(other)
if empty_self or empty_other:
return empty_self and empty_other # True if both empty
else:
return (
self._start == other._start
and self._step == other._step
and self._get_by_index(-1) == other._get_by_index(-1)
)
else:
return False
def __getitem__(self, key):
if isinstance(key, int):
return self._get_by_index(key)
elif isinstance(key, slice):
step = self._step if key.step is None else key.step * self._step
if key.start is None or key.start <= -self._len:
start = self._start
elif key.start >= self._len:
start = self._stop
else: # -self._len < key.start < self._len
start = self._get_by_index(key.start)
if key.stop is None or key.stop >= self._len:
stop = self._stop
elif key.stop <= -self._len:
stop = self._start
else: # -self._len < key.stop < self._len
stop = self._get_by_index(key.stop)
return numeric_range(start, stop, step)
else:
raise TypeError(
'numeric range indices must be '
'integers or slices, not {}'.format(type(key).__name__)
)
def __hash__(self):
if self:
return hash((self._start, self._get_by_index(-1), self._step))
else:
return self._EMPTY_HASH
def __iter__(self):
values = (self._start + (n * self._step) for n in count())
if self._growing:
return takewhile(partial(gt, self._stop), values)
else:
return takewhile(partial(lt, self._stop), values)
def __len__(self):
return self._len
def _init_len(self):
if self._growing:
start = self._start
stop = self._stop
step = self._step
else:
start = self._stop
stop = self._start
step = -self._step
distance = stop - start
if distance <= self._zero:
self._len = 0
else: # distance > 0 and step > 0: regular euclidean division
q, r = divmod(distance, step)
self._len = int(q) + int(r != self._zero)
def __reduce__(self):
return numeric_range, (self._start, self._stop, self._step)
def __repr__(self):
if self._step == 1:
return "numeric_range({}, {})".format(
repr(self._start), repr(self._stop)
)
else:
return "numeric_range({}, {}, {})".format(
repr(self._start), repr(self._stop), repr(self._step)
)
def __reversed__(self):
return iter(
numeric_range(
self._get_by_index(-1), self._start - self._step, -self._step
)
)
def count(self, value):
return int(value in self)
def index(self, value):
if self._growing:
if self._start <= value < self._stop:
q, r = divmod(value - self._start, self._step)
if r == self._zero:
return int(q)
else:
if self._start >= value > self._stop:
q, r = divmod(self._start - value, -self._step)
if r == self._zero:
return int(q)
raise ValueError("{} is not in numeric range".format(value))
def _get_by_index(self, i):
if i < 0:
i += self._len
if i < 0 or i >= self._len:
raise IndexError("numeric range object index out of range")
return self._start + i * self._step
def count_cycle(iterable, n=None):
"""Cycle through the items from *iterable* up to *n* times, yielding
the number of completed cycles along with each item. If *n* is omitted the
process repeats indefinitely.
>>> list(count_cycle('AB', 3))
[(0, 'A'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')]
"""
iterable = tuple(iterable)
if not iterable:
return iter(())
counter = count() if n is None else range(n)
return ((i, item) for i in counter for item in iterable)
def mark_ends(iterable):
"""Yield 3-tuples of the form ``(is_first, is_last, item)``.
>>> list(mark_ends('ABC'))
[(True, False, 'A'), (False, False, 'B'), (False, True, 'C')]
Use this when looping over an iterable to take special action on its first
and/or last items:
>>> iterable = ['Header', 100, 200, 'Footer']
>>> total = 0
>>> for is_first, is_last, item in mark_ends(iterable):
... if is_first:
... continue # Skip the header
... if is_last:
... continue # Skip the footer
... total += item
>>> print(total)
300
"""
it = iter(iterable)
try:
b = next(it)
except StopIteration:
return
try:
for i in count():
a = b
b = next(it)
yield i == 0, False, a
except StopIteration:
yield i == 0, True, a
def locate(iterable, pred=bool, window_size=None):
"""Yield the index of each item in *iterable* for which *pred* returns
``True``.
*pred* defaults to :func:`bool`, which will select truthy items:
>>> list(locate([0, 1, 1, 0, 1, 0, 0]))
[1, 2, 4]
Set *pred* to a custom function to, e.g., find the indexes for a particular
item.
>>> list(locate(['a', 'b', 'c', 'b'], lambda x: x == 'b'))
[1, 3]
If *window_size* is given, then the *pred* function will be called with
that many items. This enables searching for sub-sequences:
>>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
>>> pred = lambda *args: args == (1, 2, 3)
>>> list(locate(iterable, pred=pred, window_size=3))
[1, 5, 9]
Use with :func:`seekable` to find indexes and then retrieve the associated
items:
>>> from itertools import count
>>> from more_itertools import seekable
>>> source = (3 * n + 1 if (n % 2) else n // 2 for n in count())
>>> it = seekable(source)
>>> pred = lambda x: x > 100
>>> indexes = locate(it, pred=pred)
>>> i = next(indexes)
>>> it.seek(i)
>>> next(it)
106
"""
if window_size is None:
return compress(count(), map(pred, iterable))
if window_size < 1:
raise ValueError('window size must be at least 1')
it = windowed(iterable, window_size, fillvalue=_marker)
return compress(count(), starmap(pred, it))
def longest_common_prefix(iterables):
"""Yield elements of the longest common prefix amongst given *iterables*.
>>> ''.join(longest_common_prefix(['abcd', 'abc', 'abf']))
'ab'
"""
return (c[0] for c in takewhile(all_equal, zip(*iterables)))
def lstrip(iterable, pred):
"""Yield the items from *iterable*, but strip any from the beginning
for which *pred* returns ``True``.
For example, to remove a set of items from the start of an iterable:
>>> iterable = (None, False, None, 1, 2, None, 3, False, None)
>>> pred = lambda x: x in {None, False, ''}
>>> list(lstrip(iterable, pred))
[1, 2, None, 3, False, None]
This function is analogous to to :func:`str.lstrip`, and is essentially
an wrapper for :func:`itertools.dropwhile`.
"""
return dropwhile(pred, iterable)
def rstrip(iterable, pred):
"""Yield the items from *iterable*, but strip any from the end
for which *pred* returns ``True``.
For example, to remove a set of items from the end of an iterable:
>>> iterable = (None, False, None, 1, 2, None, 3, False, None)
>>> pred = lambda x: x in {None, False, ''}
>>> list(rstrip(iterable, pred))
[None, False, None, 1, 2, None, 3]
This function is analogous to :func:`str.rstrip`.
"""
cache = []
cache_append = cache.append
cache_clear = cache.clear
for x in iterable:
if pred(x):
cache_append(x)
else:
yield from cache
cache_clear()
yield x
def strip(iterable, pred):
"""Yield the items from *iterable*, but strip any from the
beginning and end for which *pred* returns ``True``.
For example, to remove a set of items from both ends of an iterable:
>>> iterable = (None, False, None, 1, 2, None, 3, False, None)
>>> pred = lambda x: x in {None, False, ''}
>>> list(strip(iterable, pred))
[1, 2, None, 3]
This function is analogous to :func:`str.strip`.
"""
return rstrip(lstrip(iterable, pred), pred)
class islice_extended:
"""An extension of :func:`itertools.islice` that supports negative values
for *stop*, *start*, and *step*.
>>> iterable = iter('abcdefgh')
>>> list(islice_extended(iterable, -4, -1))
['e', 'f', 'g']
Slices with negative values require some caching of *iterable*, but this
function takes care to minimize the amount of memory required.
For example, you can use a negative step with an infinite iterator:
>>> from itertools import count
>>> list(islice_extended(count(), 110, 99, -2))
[110, 108, 106, 104, 102, 100]
You can also use slice notation directly:
>>> iterable = map(str, count())
>>> it = islice_extended(iterable)[10:20:2]
>>> list(it)
['10', '12', '14', '16', '18']
"""
def __init__(self, iterable, *args):
it = iter(iterable)
if args:
self._iterable = _islice_helper(it, slice(*args))
else:
self._iterable = it
def __iter__(self):
return self
def __next__(self):
return next(self._iterable)
def __getitem__(self, key):
if isinstance(key, slice):
return islice_extended(_islice_helper(self._iterable, key))
raise TypeError('islice_extended.__getitem__ argument must be a slice')
def _islice_helper(it, s):
start = s.start
stop = s.stop
if s.step == 0:
raise ValueError('step argument must be a non-zero integer or None.')
step = s.step or 1
if step > 0:
start = 0 if (start is None) else start
if start < 0:
# Consume all but the last -start items
cache = deque(enumerate(it, 1), maxlen=-start)
len_iter = cache[-1][0] if cache else 0
# Adjust start to be positive
i = max(len_iter + start, 0)
# Adjust stop to be positive
if stop is None:
j = len_iter
elif stop >= 0:
j = min(stop, len_iter)
else:
j = max(len_iter + stop, 0)
# Slice the cache
n = j - i
if n <= 0:
return
for index, item in islice(cache, 0, n, step):
yield item
elif (stop is not None) and (stop < 0):
# Advance to the start position
next(islice(it, start, start), None)
# When stop is negative, we have to carry -stop items while
# iterating
cache = deque(islice(it, -stop), maxlen=-stop)
for index, item in enumerate(it):
cached_item = cache.popleft()
if index % step == 0:
yield cached_item
cache.append(item)
else:
# When both start and stop are positive we have the normal case
yield from islice(it, start, stop, step)
else:
start = -1 if (start is None) else start
if (stop is not None) and (stop < 0):
# Consume all but the last items
n = -stop - 1
cache = deque(enumerate(it, 1), maxlen=n)
len_iter = cache[-1][0] if cache else 0
# If start and stop are both negative they are comparable and
# we can just slice. Otherwise we can adjust start to be negative
# and then slice.
if start < 0:
i, j = start, stop
else:
i, j = min(start - len_iter, -1), None
for index, item in list(cache)[i:j:step]:
yield item
else:
# Advance to the stop position
if stop is not None:
m = stop + 1
next(islice(it, m, m), None)
# stop is positive, so if start is negative they are not comparable
# and we need the rest of the items.
if start < 0:
i = start
n = None
# stop is None and start is positive, so we just need items up to
# the start index.
elif stop is None:
i = None
n = start + 1
# Both stop and start are positive, so they are comparable.
else:
i = None
n = start - stop
if n <= 0:
return
cache = list(islice(it, n))
yield from cache[i::step]
def always_reversible(iterable):
"""An extension of :func:`reversed` that supports all iterables, not
just those which implement the ``Reversible`` or ``Sequence`` protocols.
>>> print(*always_reversible(x for x in range(3)))
2 1 0
If the iterable is already reversible, this function returns the
result of :func:`reversed()`. If the iterable is not reversible,
this function will cache the remaining items in the iterable and
yield them in reverse order, which may require significant storage.
"""
try:
return reversed(iterable)
except TypeError:
return reversed(list(iterable))
def consecutive_groups(iterable, ordering=lambda x: x):
"""Yield groups of consecutive items using :func:`itertools.groupby`.
The *ordering* function determines whether two items are adjacent by
returning their position.
By default, the ordering function is the identity function. This is
suitable for finding runs of numbers:
>>> iterable = [1, 10, 11, 12, 20, 30, 31, 32, 33, 40]
>>> for group in consecutive_groups(iterable):
... print(list(group))
[1]
[10, 11, 12]
[20]
[30, 31, 32, 33]
[40]
For finding runs of adjacent letters, try using the :meth:`index` method
of a string of letters:
>>> from string import ascii_lowercase
>>> iterable = 'abcdfgilmnop'
>>> ordering = ascii_lowercase.index
>>> for group in consecutive_groups(iterable, ordering):
... print(list(group))
['a', 'b', 'c', 'd']
['f', 'g']
['i']
['l', 'm', 'n', 'o', 'p']
Each group of consecutive items is an iterator that shares it source with
*iterable*. When an an output group is advanced, the previous group is
no longer available unless its elements are copied (e.g., into a ``list``).
>>> iterable = [1, 2, 11, 12, 21, 22]
>>> saved_groups = []
>>> for group in consecutive_groups(iterable):
... saved_groups.append(list(group)) # Copy group elements
>>> saved_groups
[[1, 2], [11, 12], [21, 22]]
"""
for k, g in groupby(
enumerate(iterable), key=lambda x: x[0] - ordering(x[1])
):
yield map(itemgetter(1), g)
def difference(iterable, func=sub, *, initial=None):
"""This function is the inverse of :func:`itertools.accumulate`. By default
it will compute the first difference of *iterable* using
:func:`operator.sub`:
>>> from itertools import accumulate
>>> iterable = accumulate([0, 1, 2, 3, 4]) # produces 0, 1, 3, 6, 10
>>> list(difference(iterable))
[0, 1, 2, 3, 4]
*func* defaults to :func:`operator.sub`, but other functions can be
specified. They will be applied as follows::
A, B, C, D, ... --> A, func(B, A), func(C, B), func(D, C), ...
For example, to do progressive division:
>>> iterable = [1, 2, 6, 24, 120]
>>> func = lambda x, y: x // y
>>> list(difference(iterable, func))
[1, 2, 3, 4, 5]
If the *initial* keyword is set, the first element will be skipped when
computing successive differences.
>>> it = [10, 11, 13, 16] # from accumulate([1, 2, 3], initial=10)
>>> list(difference(it, initial=10))
[1, 2, 3]
"""
a, b = tee(iterable)
try:
first = [next(b)]
except StopIteration:
return iter([])
if initial is not None:
first = []
return chain(first, map(func, b, a))
class SequenceView(Sequence):
"""Return a read-only view of the sequence object *target*.
:class:`SequenceView` objects are analogous to Python's built-in
"dictionary view" types. They provide a dynamic view of a sequence's items,
meaning that when the sequence updates, so does the view.
>>> seq = ['0', '1', '2']
>>> view = SequenceView(seq)
>>> view
SequenceView(['0', '1', '2'])
>>> seq.append('3')
>>> view
SequenceView(['0', '1', '2', '3'])
Sequence views support indexing, slicing, and length queries. They act
like the underlying sequence, except they don't allow assignment:
>>> view[1]
'1'
>>> view[1:-1]
['1', '2']
>>> len(view)
4
Sequence views are useful as an alternative to copying, as they don't
require (much) extra storage.
"""
def __init__(self, target):
if not isinstance(target, Sequence):
raise TypeError
self._target = target
def __getitem__(self, index):
return self._target[index]
def __len__(self):
return len(self._target)
def __repr__(self):
return '{}({})'.format(self.__class__.__name__, repr(self._target))
class seekable:
"""Wrap an iterator to allow for seeking backward and forward. This
progressively caches the items in the source iterable so they can be
re-visited.
Call :meth:`seek` with an index to seek to that position in the source
iterable.
To "reset" an iterator, seek to ``0``:
>>> from itertools import count
>>> it = seekable((str(n) for n in count()))
>>> next(it), next(it), next(it)
('0', '1', '2')
>>> it.seek(0)
>>> next(it), next(it), next(it)
('0', '1', '2')
>>> next(it)
'3'
You can also seek forward:
>>> it = seekable((str(n) for n in range(20)))
>>> it.seek(10)
>>> next(it)
'10'
>>> it.seek(20) # Seeking past the end of the source isn't a problem
>>> list(it)
[]
>>> it.seek(0) # Resetting works even after hitting the end
>>> next(it), next(it), next(it)
('0', '1', '2')
Call :meth:`peek` to look ahead one item without advancing the iterator:
>>> it = seekable('1234')
>>> it.peek()
'1'
>>> list(it)
['1', '2', '3', '4']
>>> it.peek(default='empty')
'empty'
Before the iterator is at its end, calling :func:`bool` on it will return
``True``. After it will return ``False``:
>>> it = seekable('5678')
>>> bool(it)
True
>>> list(it)
['5', '6', '7', '8']
>>> bool(it)
False
You may view the contents of the cache with the :meth:`elements` method.
That returns a :class:`SequenceView`, a view that updates automatically:
>>> it = seekable((str(n) for n in range(10)))
>>> next(it), next(it), next(it)
('0', '1', '2')
>>> elements = it.elements()
>>> elements
SequenceView(['0', '1', '2'])
>>> next(it)
'3'
>>> elements
SequenceView(['0', '1', '2', '3'])
By default, the cache grows as the source iterable progresses, so beware of
wrapping very large or infinite iterables. Supply *maxlen* to limit the
size of the cache (this of course limits how far back you can seek).
>>> from itertools import count
>>> it = seekable((str(n) for n in count()), maxlen=2)
>>> next(it), next(it), next(it), next(it)
('0', '1', '2', '3')
>>> list(it.elements())
['2', '3']
>>> it.seek(0)
>>> next(it), next(it), next(it), next(it)
('2', '3', '4', '5')
>>> next(it)
'6'
"""
def __init__(self, iterable, maxlen=None):
self._source = iter(iterable)
if maxlen is None:
self._cache = []
else:
self._cache = deque([], maxlen)
self._index = None
def __iter__(self):
return self
def __next__(self):
if self._index is not None:
try:
item = self._cache[self._index]
except IndexError:
self._index = None
else:
self._index += 1
return item
item = next(self._source)
self._cache.append(item)
return item
def __bool__(self):
try:
self.peek()
except StopIteration:
return False
return True
def peek(self, default=_marker):
try:
peeked = next(self)
except StopIteration:
if default is _marker:
raise
return default
if self._index is None:
self._index = len(self._cache)
self._index -= 1
return peeked
def elements(self):
return SequenceView(self._cache)
def seek(self, index):
self._index = index
remainder = index - len(self._cache)
if remainder > 0:
consume(self, remainder)
class run_length:
"""
:func:`run_length.encode` compresses an iterable with run-length encoding.
It yields groups of repeated items with the count of how many times they
were repeated:
>>> uncompressed = 'abbcccdddd'
>>> list(run_length.encode(uncompressed))
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
:func:`run_length.decode` decompresses an iterable that was previously
compressed with run-length encoding. It yields the items of the
decompressed iterable:
>>> compressed = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> list(run_length.decode(compressed))
['a', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'd']
"""
@staticmethod
def encode(iterable):
return ((k, ilen(g)) for k, g in groupby(iterable))
@staticmethod
def decode(iterable):
return chain.from_iterable(repeat(k, n) for k, n in iterable)
def exactly_n(iterable, n, predicate=bool):
"""Return ``True`` if exactly ``n`` items in the iterable are ``True``
according to the *predicate* function.
>>> exactly_n([True, True, False], 2)
True
>>> exactly_n([True, True, False], 1)
False
>>> exactly_n([0, 1, 2, 3, 4, 5], 3, lambda x: x < 3)
True
The iterable will be advanced until ``n + 1`` truthy items are encountered,
so avoid calling it on infinite iterables.
"""
return len(take(n + 1, filter(predicate, iterable))) == n
def circular_shifts(iterable):
"""Return a list of circular shifts of *iterable*.
>>> circular_shifts(range(4))
[(0, 1, 2, 3), (1, 2, 3, 0), (2, 3, 0, 1), (3, 0, 1, 2)]
"""
lst = list(iterable)
return take(len(lst), windowed(cycle(lst), len(lst)))
def make_decorator(wrapping_func, result_index=0):
"""Return a decorator version of *wrapping_func*, which is a function that
modifies an iterable. *result_index* is the position in that function's
signature where the iterable goes.
This lets you use itertools on the "production end," i.e. at function
definition. This can augment what the function returns without changing the
function's code.
For example, to produce a decorator version of :func:`chunked`:
>>> from more_itertools import chunked
>>> chunker = make_decorator(chunked, result_index=0)
>>> @chunker(3)
... def iter_range(n):
... return iter(range(n))
...
>>> list(iter_range(9))
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
To only allow truthy items to be returned:
>>> truth_serum = make_decorator(filter, result_index=1)
>>> @truth_serum(bool)
... def boolean_test():
... return [0, 1, '', ' ', False, True]
...
>>> list(boolean_test())
[1, ' ', True]
The :func:`peekable` and :func:`seekable` wrappers make for practical
decorators:
>>> from more_itertools import peekable
>>> peekable_function = make_decorator(peekable)
>>> @peekable_function()
... def str_range(*args):
... return (str(x) for x in range(*args))
...
>>> it = str_range(1, 20, 2)
>>> next(it), next(it), next(it)
('1', '3', '5')
>>> it.peek()
'7'
>>> next(it)
'7'
"""
# See https://sites.google.com/site/bbayles/index/decorator_factory for
# notes on how this works.
def decorator(*wrapping_args, **wrapping_kwargs):
def outer_wrapper(f):
def inner_wrapper(*args, **kwargs):
result = f(*args, **kwargs)
wrapping_args_ = list(wrapping_args)
wrapping_args_.insert(result_index, result)
return wrapping_func(*wrapping_args_, **wrapping_kwargs)
return inner_wrapper
return outer_wrapper
return decorator
def map_reduce(iterable, keyfunc, valuefunc=None, reducefunc=None):
"""Return a dictionary that maps the items in *iterable* to categories
defined by *keyfunc*, transforms them with *valuefunc*, and
then summarizes them by category with *reducefunc*.
*valuefunc* defaults to the identity function if it is unspecified.
If *reducefunc* is unspecified, no summarization takes place:
>>> keyfunc = lambda x: x.upper()
>>> result = map_reduce('abbccc', keyfunc)
>>> sorted(result.items())
[('A', ['a']), ('B', ['b', 'b']), ('C', ['c', 'c', 'c'])]
Specifying *valuefunc* transforms the categorized items:
>>> keyfunc = lambda x: x.upper()
>>> valuefunc = lambda x: 1
>>> result = map_reduce('abbccc', keyfunc, valuefunc)
>>> sorted(result.items())
[('A', [1]), ('B', [1, 1]), ('C', [1, 1, 1])]
Specifying *reducefunc* summarizes the categorized items:
>>> keyfunc = lambda x: x.upper()
>>> valuefunc = lambda x: 1
>>> reducefunc = sum
>>> result = map_reduce('abbccc', keyfunc, valuefunc, reducefunc)
>>> sorted(result.items())
[('A', 1), ('B', 2), ('C', 3)]
You may want to filter the input iterable before applying the map/reduce
procedure:
>>> all_items = range(30)
>>> items = [x for x in all_items if 10 <= x <= 20] # Filter
>>> keyfunc = lambda x: x % 2 # Evens map to 0; odds to 1
>>> categories = map_reduce(items, keyfunc=keyfunc)
>>> sorted(categories.items())
[(0, [10, 12, 14, 16, 18, 20]), (1, [11, 13, 15, 17, 19])]
>>> summaries = map_reduce(items, keyfunc=keyfunc, reducefunc=sum)
>>> sorted(summaries.items())
[(0, 90), (1, 75)]
Note that all items in the iterable are gathered into a list before the
summarization step, which may require significant storage.
The returned object is a :obj:`collections.defaultdict` with the
``default_factory`` set to ``None``, such that it behaves like a normal
dictionary.
"""
valuefunc = (lambda x: x) if (valuefunc is None) else valuefunc
ret = defaultdict(list)
for item in iterable:
key = keyfunc(item)
value = valuefunc(item)
ret[key].append(value)
if reducefunc is not None:
for key, value_list in ret.items():
ret[key] = reducefunc(value_list)
ret.default_factory = None
return ret
def rlocate(iterable, pred=bool, window_size=None):
"""Yield the index of each item in *iterable* for which *pred* returns
``True``, starting from the right and moving left.
*pred* defaults to :func:`bool`, which will select truthy items:
>>> list(rlocate([0, 1, 1, 0, 1, 0, 0])) # Truthy at 1, 2, and 4
[4, 2, 1]
Set *pred* to a custom function to, e.g., find the indexes for a particular
item:
>>> iterable = iter('abcb')
>>> pred = lambda x: x == 'b'
>>> list(rlocate(iterable, pred))
[3, 1]
If *window_size* is given, then the *pred* function will be called with
that many items. This enables searching for sub-sequences:
>>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
>>> pred = lambda *args: args == (1, 2, 3)
>>> list(rlocate(iterable, pred=pred, window_size=3))
[9, 5, 1]
Beware, this function won't return anything for infinite iterables.
If *iterable* is reversible, ``rlocate`` will reverse it and search from
the right. Otherwise, it will search from the left and return the results
in reverse order.
See :func:`locate` to for other example applications.
"""
if window_size is None:
try:
len_iter = len(iterable)
return (len_iter - i - 1 for i in locate(reversed(iterable), pred))
except TypeError:
pass
return reversed(list(locate(iterable, pred, window_size)))
def replace(iterable, pred, substitutes, count=None, window_size=1):
"""Yield the items from *iterable*, replacing the items for which *pred*
returns ``True`` with the items from the iterable *substitutes*.
>>> iterable = [1, 1, 0, 1, 1, 0, 1, 1]
>>> pred = lambda x: x == 0
>>> substitutes = (2, 3)
>>> list(replace(iterable, pred, substitutes))
[1, 1, 2, 3, 1, 1, 2, 3, 1, 1]
If *count* is given, the number of replacements will be limited:
>>> iterable = [1, 1, 0, 1, 1, 0, 1, 1, 0]
>>> pred = lambda x: x == 0
>>> substitutes = [None]
>>> list(replace(iterable, pred, substitutes, count=2))
[1, 1, None, 1, 1, None, 1, 1, 0]
Use *window_size* to control the number of items passed as arguments to
*pred*. This allows for locating and replacing subsequences.
>>> iterable = [0, 1, 2, 5, 0, 1, 2, 5]
>>> window_size = 3
>>> pred = lambda *args: args == (0, 1, 2) # 3 items passed to pred
>>> substitutes = [3, 4] # Splice in these items
>>> list(replace(iterable, pred, substitutes, window_size=window_size))
[3, 4, 5, 3, 4, 5]
"""
if window_size < 1:
raise ValueError('window_size must be at least 1')
# Save the substitutes iterable, since it's used more than once
substitutes = tuple(substitutes)
# Add padding such that the number of windows matches the length of the
# iterable
it = chain(iterable, [_marker] * (window_size - 1))
windows = windowed(it, window_size)
n = 0
for w in windows:
# If the current window matches our predicate (and we haven't hit
# our maximum number of replacements), splice in the substitutes
# and then consume the following windows that overlap with this one.
# For example, if the iterable is (0, 1, 2, 3, 4...)
# and the window size is 2, we have (0, 1), (1, 2), (2, 3)...
# If the predicate matches on (0, 1), we need to zap (0, 1) and (1, 2)
if pred(*w):
if (count is None) or (n < count):
n += 1
yield from substitutes
consume(windows, window_size - 1)
continue
# If there was no match (or we've reached the replacement limit),
# yield the first item from the window.
if w and (w[0] is not _marker):
yield w[0]
def partitions(iterable):
"""Yield all possible order-preserving partitions of *iterable*.
>>> iterable = 'abc'
>>> for part in partitions(iterable):
... print([''.join(p) for p in part])
['abc']
['a', 'bc']
['ab', 'c']
['a', 'b', 'c']
This is unrelated to :func:`partition`.
"""
sequence = list(iterable)
n = len(sequence)
for i in powerset(range(1, n)):
yield [sequence[i:j] for i, j in zip((0,) + i, i + (n,))]
def set_partitions(iterable, k=None):
"""
Yield the set partitions of *iterable* into *k* parts. Set partitions are
not order-preserving.
>>> iterable = 'abc'
>>> for part in set_partitions(iterable, 2):
... print([''.join(p) for p in part])
['a', 'bc']
['ab', 'c']
['b', 'ac']
If *k* is not given, every set partition is generated.
>>> iterable = 'abc'
>>> for part in set_partitions(iterable):
... print([''.join(p) for p in part])
['abc']
['a', 'bc']
['ab', 'c']
['b', 'ac']
['a', 'b', 'c']
"""
L = list(iterable)
n = len(L)
if k is not None:
if k < 1:
raise ValueError(
"Can't partition in a negative or zero number of groups"
)
elif k > n:
return
def set_partitions_helper(L, k):
n = len(L)
if k == 1:
yield [L]
elif n == k:
yield [[s] for s in L]
else:
e, *M = L
for p in set_partitions_helper(M, k - 1):
yield [[e], *p]
for p in set_partitions_helper(M, k):
for i in range(len(p)):
yield p[:i] + [[e] + p[i]] + p[i + 1 :]
if k is None:
for k in range(1, n + 1):
yield from set_partitions_helper(L, k)
else:
yield from set_partitions_helper(L, k)
class time_limited:
"""
Yield items from *iterable* until *limit_seconds* have passed.
If the time limit expires before all items have been yielded, the
``timed_out`` parameter will be set to ``True``.
>>> from time import sleep
>>> def generator():
... yield 1
... yield 2
... sleep(0.2)
... yield 3
>>> iterable = time_limited(0.1, generator())
>>> list(iterable)
[1, 2]
>>> iterable.timed_out
True
Note that the time is checked before each item is yielded, and iteration
stops if the time elapsed is greater than *limit_seconds*. If your time
limit is 1 second, but it takes 2 seconds to generate the first item from
the iterable, the function will run for 2 seconds and not yield anything.
"""
def __init__(self, limit_seconds, iterable):
if limit_seconds < 0:
raise ValueError('limit_seconds must be positive')
self.limit_seconds = limit_seconds
self._iterable = iter(iterable)
self._start_time = monotonic()
self.timed_out = False
def __iter__(self):
return self
def __next__(self):
item = next(self._iterable)
if monotonic() - self._start_time > self.limit_seconds:
self.timed_out = True
raise StopIteration
return item
def only(iterable, default=None, too_long=None):
"""If *iterable* has only one item, return it.
If it has zero items, return *default*.
If it has more than one item, raise the exception given by *too_long*,
which is ``ValueError`` by default.
>>> only([], default='missing')
'missing'
>>> only([1])
1
>>> only([1, 2]) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValueError: Expected exactly one item in iterable, but got 1, 2,
and perhaps more.'
>>> only([1, 2], too_long=TypeError) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError
Note that :func:`only` attempts to advance *iterable* twice to ensure there
is only one item. See :func:`spy` or :func:`peekable` to check
iterable contents less destructively.
"""
it = iter(iterable)
first_value = next(it, default)
try:
second_value = next(it)
except StopIteration:
pass
else:
msg = (
'Expected exactly one item in iterable, but got {!r}, {!r}, '
'and perhaps more.'.format(first_value, second_value)
)
raise too_long or ValueError(msg)
return first_value
class _IChunk:
def __init__(self, iterable, n):
self._it = islice(iterable, n)
self._cache = deque()
def fill_cache(self):
self._cache.extend(self._it)
def __iter__(self):
return self
def __next__(self):
try:
return next(self._it)
except StopIteration:
if self._cache:
return self._cache.popleft()
else:
raise
def ichunked(iterable, n):
"""Break *iterable* into sub-iterables with *n* elements each.
:func:`ichunked` is like :func:`chunked`, but it yields iterables
instead of lists.
If the sub-iterables are read in order, the elements of *iterable*
won't be stored in memory.
If they are read out of order, :func:`itertools.tee` is used to cache
elements as necessary.
>>> from itertools import count
>>> all_chunks = ichunked(count(), 4)
>>> c_1, c_2, c_3 = next(all_chunks), next(all_chunks), next(all_chunks)
>>> list(c_2) # c_1's elements have been cached; c_3's haven't been
[4, 5, 6, 7]
>>> list(c_1)
[0, 1, 2, 3]
>>> list(c_3)
[8, 9, 10, 11]
"""
source = peekable(iter(iterable))
ichunk_marker = object()
while True:
# Check to see whether we're at the end of the source iterable
item = source.peek(ichunk_marker)
if item is ichunk_marker:
return
chunk = _IChunk(source, n)
yield chunk
# Advance the source iterable and fill previous chunk's cache
chunk.fill_cache()
def iequals(*iterables):
"""Return ``True`` if all given *iterables* are equal to each other,
which means that they contain the same elements in the same order.
The function is useful for comparing iterables of different data types
or iterables that do not support equality checks.
>>> iequals("abc", ['a', 'b', 'c'], ('a', 'b', 'c'), iter("abc"))
True
>>> iequals("abc", "acb")
False
Not to be confused with :func:`all_equals`, which checks whether all
elements of iterable are equal to each other.
"""
return all(map(all_equal, zip_longest(*iterables, fillvalue=object())))
def distinct_combinations(iterable, r):
"""Yield the distinct combinations of *r* items taken from *iterable*.
>>> list(distinct_combinations([0, 0, 1], 2))
[(0, 0), (0, 1)]
Equivalent to ``set(combinations(iterable))``, except duplicates are not
generated and thrown away. For larger input sequences this is much more
efficient.
"""
if r < 0:
raise ValueError('r must be non-negative')
elif r == 0:
yield ()
return
pool = tuple(iterable)
generators = [unique_everseen(enumerate(pool), key=itemgetter(1))]
current_combo = [None] * r
level = 0
while generators:
try:
cur_idx, p = next(generators[-1])
except StopIteration:
generators.pop()
level -= 1
continue
current_combo[level] = p
if level + 1 == r:
yield tuple(current_combo)
else:
generators.append(
unique_everseen(
enumerate(pool[cur_idx + 1 :], cur_idx + 1),
key=itemgetter(1),
)
)
level += 1
def filter_except(validator, iterable, *exceptions):
"""Yield the items from *iterable* for which the *validator* function does
not raise one of the specified *exceptions*.
*validator* is called for each item in *iterable*.
It should be a function that accepts one argument and raises an exception
if that item is not valid.
>>> iterable = ['1', '2', 'three', '4', None]
>>> list(filter_except(int, iterable, ValueError, TypeError))
['1', '2', '4']
If an exception other than one given by *exceptions* is raised by
*validator*, it is raised like normal.
"""
for item in iterable:
try:
validator(item)
except exceptions:
pass
else:
yield item
def map_except(function, iterable, *exceptions):
"""Transform each item from *iterable* with *function* and yield the
result, unless *function* raises one of the specified *exceptions*.
*function* is called to transform each item in *iterable*.
It should accept one argument.
>>> iterable = ['1', '2', 'three', '4', None]
>>> list(map_except(int, iterable, ValueError, TypeError))
[1, 2, 4]
If an exception other than one given by *exceptions* is raised by
*function*, it is raised like normal.
"""
for item in iterable:
try:
yield function(item)
except exceptions:
pass
def map_if(iterable, pred, func, func_else=lambda x: x):
"""Evaluate each item from *iterable* using *pred*. If the result is
equivalent to ``True``, transform the item with *func* and yield it.
Otherwise, transform the item with *func_else* and yield it.
*pred*, *func*, and *func_else* should each be functions that accept
one argument. By default, *func_else* is the identity function.
>>> from math import sqrt
>>> iterable = list(range(-5, 5))
>>> iterable
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
>>> list(map_if(iterable, lambda x: x > 3, lambda x: 'toobig'))
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 'toobig']
>>> list(map_if(iterable, lambda x: x >= 0,
... lambda x: f'{sqrt(x):.2f}', lambda x: None))
[None, None, None, None, None, '0.00', '1.00', '1.41', '1.73', '2.00']
"""
for item in iterable:
yield func(item) if pred(item) else func_else(item)
def _sample_unweighted(iterable, k):
# Implementation of "Algorithm L" from the 1994 paper by Kim-Hung Li:
# "Reservoir-Sampling Algorithms of Time Complexity O(n(1+log(N/n)))".
# Fill up the reservoir (collection of samples) with the first `k` samples
reservoir = take(k, iterable)
# Generate random number that's the largest in a sample of k U(0,1) numbers
# Largest order statistic: https://en.wikipedia.org/wiki/Order_statistic
W = exp(log(random()) / k)
# The number of elements to skip before changing the reservoir is a random
# number with a geometric distribution. Sample it using random() and logs.
next_index = k + floor(log(random()) / log(1 - W))
for index, element in enumerate(iterable, k):
if index == next_index:
reservoir[randrange(k)] = element
# The new W is the largest in a sample of k U(0, `old_W`) numbers
W *= exp(log(random()) / k)
next_index += floor(log(random()) / log(1 - W)) + 1
return reservoir
def _sample_weighted(iterable, k, weights):
# Implementation of "A-ExpJ" from the 2006 paper by Efraimidis et al. :
# "Weighted random sampling with a reservoir".
# Log-transform for numerical stability for weights that are small/large
weight_keys = (log(random()) / weight for weight in weights)
# Fill up the reservoir (collection of samples) with the first `k`
# weight-keys and elements, then heapify the list.
reservoir = take(k, zip(weight_keys, iterable))
heapify(reservoir)
# The number of jumps before changing the reservoir is a random variable
# with an exponential distribution. Sample it using random() and logs.
smallest_weight_key, _ = reservoir[0]
weights_to_skip = log(random()) / smallest_weight_key
for weight, element in zip(weights, iterable):
if weight >= weights_to_skip:
# The notation here is consistent with the paper, but we store
# the weight-keys in log-space for better numerical stability.
smallest_weight_key, _ = reservoir[0]
t_w = exp(weight * smallest_weight_key)
r_2 = uniform(t_w, 1) # generate U(t_w, 1)
weight_key = log(r_2) / weight
heapreplace(reservoir, (weight_key, element))
smallest_weight_key, _ = reservoir[0]
weights_to_skip = log(random()) / smallest_weight_key
else:
weights_to_skip -= weight
# Equivalent to [element for weight_key, element in sorted(reservoir)]
return [heappop(reservoir)[1] for _ in range(k)]
def sample(iterable, k, weights=None):
"""Return a *k*-length list of elements chosen (without replacement)
from the *iterable*. Like :func:`random.sample`, but works on iterables
of unknown length.
>>> iterable = range(100)
>>> sample(iterable, 5) # doctest: +SKIP
[81, 60, 96, 16, 4]
An iterable with *weights* may also be given:
>>> iterable = range(100)
>>> weights = (i * i + 1 for i in range(100))
>>> sampled = sample(iterable, 5, weights=weights) # doctest: +SKIP
[79, 67, 74, 66, 78]
The algorithm can also be used to generate weighted random permutations.
The relative weight of each item determines the probability that it
appears late in the permutation.
>>> data = "abcdefgh"
>>> weights = range(1, len(data) + 1)
>>> sample(data, k=len(data), weights=weights) # doctest: +SKIP
['c', 'a', 'b', 'e', 'g', 'd', 'h', 'f']
"""
if k == 0:
return []
iterable = iter(iterable)
if weights is None:
return _sample_unweighted(iterable, k)
else:
weights = iter(weights)
return _sample_weighted(iterable, k, weights)
def is_sorted(iterable, key=None, reverse=False, strict=False):
"""Returns ``True`` if the items of iterable are in sorted order, and
``False`` otherwise. *key* and *reverse* have the same meaning that they do
in the built-in :func:`sorted` function.
>>> is_sorted(['1', '2', '3', '4', '5'], key=int)
True
>>> is_sorted([5, 4, 3, 1, 2], reverse=True)
False
If *strict*, tests for strict sorting, that is, returns ``False`` if equal
elements are found:
>>> is_sorted([1, 2, 2])
True
>>> is_sorted([1, 2, 2], strict=True)
False
The function returns ``False`` after encountering the first out-of-order
item. If there are no out-of-order items, the iterable is exhausted.
"""
compare = (le if reverse else ge) if strict else (lt if reverse else gt)
it = iterable if key is None else map(key, iterable)
return not any(starmap(compare, pairwise(it)))
class AbortThread(BaseException):
pass
class callback_iter:
"""Convert a function that uses callbacks to an iterator.
Let *func* be a function that takes a `callback` keyword argument.
For example:
>>> def func(callback=None):
... for i, c in [(1, 'a'), (2, 'b'), (3, 'c')]:
... if callback:
... callback(i, c)
... return 4
Use ``with callback_iter(func)`` to get an iterator over the parameters
that are delivered to the callback.
>>> with callback_iter(func) as it:
... for args, kwargs in it:
... print(args)
(1, 'a')
(2, 'b')
(3, 'c')
The function will be called in a background thread. The ``done`` property
indicates whether it has completed execution.
>>> it.done
True
If it completes successfully, its return value will be available
in the ``result`` property.
>>> it.result
4
Notes:
* If the function uses some keyword argument besides ``callback``, supply
*callback_kwd*.
* If it finished executing, but raised an exception, accessing the
``result`` property will raise the same exception.
* If it hasn't finished executing, accessing the ``result``
property from within the ``with`` block will raise ``RuntimeError``.
* If it hasn't finished executing, accessing the ``result`` property from
outside the ``with`` block will raise a
``more_itertools.AbortThread`` exception.
* Provide *wait_seconds* to adjust how frequently the it is polled for
output.
"""
def __init__(self, func, callback_kwd='callback', wait_seconds=0.1):
self._func = func
self._callback_kwd = callback_kwd
self._aborted = False
self._future = None
self._wait_seconds = wait_seconds
# Lazily import concurrent.future
self._executor = __import__(
'concurrent.futures'
).futures.ThreadPoolExecutor(max_workers=1)
self._iterator = self._reader()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self._aborted = True
self._executor.shutdown()
def __iter__(self):
return self
def __next__(self):
return next(self._iterator)
@property
def done(self):
if self._future is None:
return False
return self._future.done()
@property
def result(self):
if not self.done:
raise RuntimeError('Function has not yet completed')
return self._future.result()
def _reader(self):
q = Queue()
def callback(*args, **kwargs):
if self._aborted:
raise AbortThread('canceled by user')
q.put((args, kwargs))
self._future = self._executor.submit(
self._func, **{self._callback_kwd: callback}
)
while True:
try:
item = q.get(timeout=self._wait_seconds)
except Empty:
pass
else:
q.task_done()
yield item
if self._future.done():
break
remaining = []
while True:
try:
item = q.get_nowait()
except Empty:
break
else:
q.task_done()
remaining.append(item)
q.join()
yield from remaining
def windowed_complete(iterable, n):
"""
Yield ``(beginning, middle, end)`` tuples, where:
* Each ``middle`` has *n* items from *iterable*
* Each ``beginning`` has the items before the ones in ``middle``
* Each ``end`` has the items after the ones in ``middle``
>>> iterable = range(7)
>>> n = 3
>>> for beginning, middle, end in windowed_complete(iterable, n):
... print(beginning, middle, end)
() (0, 1, 2) (3, 4, 5, 6)
(0,) (1, 2, 3) (4, 5, 6)
(0, 1) (2, 3, 4) (5, 6)
(0, 1, 2) (3, 4, 5) (6,)
(0, 1, 2, 3) (4, 5, 6) ()
Note that *n* must be at least 0 and most equal to the length of
*iterable*.
This function will exhaust the iterable and may require significant
storage.
"""
if n < 0:
raise ValueError('n must be >= 0')
seq = tuple(iterable)
size = len(seq)
if n > size:
raise ValueError('n must be <= len(seq)')
for i in range(size - n + 1):
beginning = seq[:i]
middle = seq[i : i + n]
end = seq[i + n :]
yield beginning, middle, end
def all_unique(iterable, key=None):
"""
Returns ``True`` if all the elements of *iterable* are unique (no two
elements are equal).
>>> all_unique('ABCB')
False
If a *key* function is specified, it will be used to make comparisons.
>>> all_unique('ABCb')
True
>>> all_unique('ABCb', str.lower)
False
The function returns as soon as the first non-unique element is
encountered. Iterables with a mix of hashable and unhashable items can
be used, but the function will be slower for unhashable items.
"""
seenset = set()
seenset_add = seenset.add
seenlist = []
seenlist_add = seenlist.append
for element in map(key, iterable) if key else iterable:
try:
if element in seenset:
return False
seenset_add(element)
except TypeError:
if element in seenlist:
return False
seenlist_add(element)
return True
def nth_product(index, *args):
"""Equivalent to ``list(product(*args))[index]``.
The products of *args* can be ordered lexicographically.
:func:`nth_product` computes the product at sort position *index* without
computing the previous products.
>>> nth_product(8, range(2), range(2), range(2), range(2))
(1, 0, 0, 0)
``IndexError`` will be raised if the given *index* is invalid.
"""
pools = list(map(tuple, reversed(args)))
ns = list(map(len, pools))
c = reduce(mul, ns)
if index < 0:
index += c
if not 0 <= index < c:
raise IndexError
result = []
for pool, n in zip(pools, ns):
result.append(pool[index % n])
index //= n
return tuple(reversed(result))
def nth_permutation(iterable, r, index):
"""Equivalent to ``list(permutations(iterable, r))[index]```
The subsequences of *iterable* that are of length *r* where order is
important can be ordered lexicographically. :func:`nth_permutation`
computes the subsequence at sort position *index* directly, without
computing the previous subsequences.
>>> nth_permutation('ghijk', 2, 5)
('h', 'i')
``ValueError`` will be raised If *r* is negative or greater than the length
of *iterable*.
``IndexError`` will be raised if the given *index* is invalid.
"""
pool = list(iterable)
n = len(pool)
if r is None or r == n:
r, c = n, factorial(n)
elif not 0 <= r < n:
raise ValueError
else:
c = factorial(n) // factorial(n - r)
if index < 0:
index += c
if not 0 <= index < c:
raise IndexError
if c == 0:
return tuple()
result = [0] * r
q = index * factorial(n) // c if r < n else index
for d in range(1, n + 1):
q, i = divmod(q, d)
if 0 <= n - d < r:
result[n - d] = i
if q == 0:
break
return tuple(map(pool.pop, result))
def value_chain(*args):
"""Yield all arguments passed to the function in the same order in which
they were passed. If an argument itself is iterable then iterate over its
values.
>>> list(value_chain(1, 2, 3, [4, 5, 6]))
[1, 2, 3, 4, 5, 6]
Binary and text strings are not considered iterable and are emitted
as-is:
>>> list(value_chain('12', '34', ['56', '78']))
['12', '34', '56', '78']
Multiple levels of nesting are not flattened.
"""
for value in args:
if isinstance(value, (str, bytes)):
yield value
continue
try:
yield from value
except TypeError:
yield value
def product_index(element, *args):
"""Equivalent to ``list(product(*args)).index(element)``
The products of *args* can be ordered lexicographically.
:func:`product_index` computes the first index of *element* without
computing the previous products.
>>> product_index([8, 2], range(10), range(5))
42
``ValueError`` will be raised if the given *element* isn't in the product
of *args*.
"""
index = 0
for x, pool in zip_longest(element, args, fillvalue=_marker):
if x is _marker or pool is _marker:
raise ValueError('element is not a product of args')
pool = tuple(pool)
index = index * len(pool) + pool.index(x)
return index
def combination_index(element, iterable):
"""Equivalent to ``list(combinations(iterable, r)).index(element)``
The subsequences of *iterable* that are of length *r* can be ordered
lexicographically. :func:`combination_index` computes the index of the
first *element*, without computing the previous combinations.
>>> combination_index('adf', 'abcdefg')
10
``ValueError`` will be raised if the given *element* isn't one of the
combinations of *iterable*.
"""
element = enumerate(element)
k, y = next(element, (None, None))
if k is None:
return 0
indexes = []
pool = enumerate(iterable)
for n, x in pool:
if x == y:
indexes.append(n)
tmp, y = next(element, (None, None))
if tmp is None:
break
else:
k = tmp
else:
raise ValueError('element is not a combination of iterable')
n, _ = last(pool, default=(n, None))
# Python versions below 3.8 don't have math.comb
index = 1
for i, j in enumerate(reversed(indexes), start=1):
j = n - j
if i <= j:
index += factorial(j) // (factorial(i) * factorial(j - i))
return factorial(n + 1) // (factorial(k + 1) * factorial(n - k)) - index
def permutation_index(element, iterable):
"""Equivalent to ``list(permutations(iterable, r)).index(element)```
The subsequences of *iterable* that are of length *r* where order is
important can be ordered lexicographically. :func:`permutation_index`
computes the index of the first *element* directly, without computing
the previous permutations.
>>> permutation_index([1, 3, 2], range(5))
19
``ValueError`` will be raised if the given *element* isn't one of the
permutations of *iterable*.
"""
index = 0
pool = list(iterable)
for i, x in zip(range(len(pool), -1, -1), element):
r = pool.index(x)
index = index * i + r
del pool[r]
return index
class countable:
"""Wrap *iterable* and keep a count of how many items have been consumed.
The ``items_seen`` attribute starts at ``0`` and increments as the iterable
is consumed:
>>> iterable = map(str, range(10))
>>> it = countable(iterable)
>>> it.items_seen
0
>>> next(it), next(it)
('0', '1')
>>> list(it)
['2', '3', '4', '5', '6', '7', '8', '9']
>>> it.items_seen
10
"""
def __init__(self, iterable):
self._it = iter(iterable)
self.items_seen = 0
def __iter__(self):
return self
def __next__(self):
item = next(self._it)
self.items_seen += 1
return item
def chunked_even(iterable, n):
"""Break *iterable* into lists of approximately length *n*.
Items are distributed such the lengths of the lists differ by at most
1 item.
>>> iterable = [1, 2, 3, 4, 5, 6, 7]
>>> n = 3
>>> list(chunked_even(iterable, n)) # List lengths: 3, 2, 2
[[1, 2, 3], [4, 5], [6, 7]]
>>> list(chunked(iterable, n)) # List lengths: 3, 3, 1
[[1, 2, 3], [4, 5, 6], [7]]
"""
len_method = getattr(iterable, '__len__', None)
if len_method is None:
return _chunked_even_online(iterable, n)
else:
return _chunked_even_finite(iterable, len_method(), n)
def _chunked_even_online(iterable, n):
buffer = []
maxbuf = n + (n - 2) * (n - 1)
for x in iterable:
buffer.append(x)
if len(buffer) == maxbuf:
yield buffer[:n]
buffer = buffer[n:]
yield from _chunked_even_finite(buffer, len(buffer), n)
def _chunked_even_finite(iterable, N, n):
if N < 1:
return
# Lists are either size `full_size <= n` or `partial_size = full_size - 1`
q, r = divmod(N, n)
num_lists = q + (1 if r > 0 else 0)
q, r = divmod(N, num_lists)
full_size = q + (1 if r > 0 else 0)
partial_size = full_size - 1
num_full = N - partial_size * num_lists
num_partial = num_lists - num_full
buffer = []
iterator = iter(iterable)
# Yield num_full lists of full_size
for x in iterator:
buffer.append(x)
if len(buffer) == full_size:
yield buffer
buffer = []
num_full -= 1
if num_full <= 0:
break
# Yield num_partial lists of partial_size
for x in iterator:
buffer.append(x)
if len(buffer) == partial_size:
yield buffer
buffer = []
num_partial -= 1
def zip_broadcast(*objects, scalar_types=(str, bytes), strict=False):
"""A version of :func:`zip` that "broadcasts" any scalar
(i.e., non-iterable) items into output tuples.
>>> iterable_1 = [1, 2, 3]
>>> iterable_2 = ['a', 'b', 'c']
>>> scalar = '_'
>>> list(zip_broadcast(iterable_1, iterable_2, scalar))
[(1, 'a', '_'), (2, 'b', '_'), (3, 'c', '_')]
The *scalar_types* keyword argument determines what types are considered
scalar. It is set to ``(str, bytes)`` by default. Set it to ``None`` to
treat strings and byte strings as iterable:
>>> list(zip_broadcast('abc', 0, 'xyz', scalar_types=None))
[('a', 0, 'x'), ('b', 0, 'y'), ('c', 0, 'z')]
If the *strict* keyword argument is ``True``, then
``UnequalIterablesError`` will be raised if any of the iterables have
different lengths.
"""
def is_scalar(obj):
if scalar_types and isinstance(obj, scalar_types):
return True
try:
iter(obj)
except TypeError:
return True
else:
return False
size = len(objects)
if not size:
return
iterables, iterable_positions = [], []
scalars, scalar_positions = [], []
for i, obj in enumerate(objects):
if is_scalar(obj):
scalars.append(obj)
scalar_positions.append(i)
else:
iterables.append(iter(obj))
iterable_positions.append(i)
if len(scalars) == size:
yield tuple(objects)
return
zipper = _zip_equal if strict else zip
for item in zipper(*iterables):
new_item = [None] * size
for i, elem in zip(iterable_positions, item):
new_item[i] = elem
for i, elem in zip(scalar_positions, scalars):
new_item[i] = elem
yield tuple(new_item)
def unique_in_window(iterable, n, key=None):
"""Yield the items from *iterable* that haven't been seen recently.
*n* is the size of the lookback window.
>>> iterable = [0, 1, 0, 2, 3, 0]
>>> n = 3
>>> list(unique_in_window(iterable, n))
[0, 1, 2, 3, 0]
The *key* function, if provided, will be used to determine uniqueness:
>>> list(unique_in_window('abAcda', 3, key=lambda x: x.lower()))
['a', 'b', 'c', 'd', 'a']
The items in *iterable* must be hashable.
"""
if n <= 0:
raise ValueError('n must be greater than 0')
window = deque(maxlen=n)
uniques = set()
use_key = key is not None
for item in iterable:
k = key(item) if use_key else item
if k in uniques:
continue
if len(uniques) == n:
uniques.discard(window[0])
uniques.add(k)
window.append(k)
yield item
def duplicates_everseen(iterable, key=None):
"""Yield duplicate elements after their first appearance.
>>> list(duplicates_everseen('mississippi'))
['s', 'i', 's', 's', 'i', 'p', 'i']
>>> list(duplicates_everseen('AaaBbbCccAaa', str.lower))
['a', 'a', 'b', 'b', 'c', 'c', 'A', 'a', 'a']
This function is analagous to :func:`unique_everseen` and is subject to
the same performance considerations.
"""
seen_set = set()
seen_list = []
use_key = key is not None
for element in iterable:
k = key(element) if use_key else element
try:
if k not in seen_set:
seen_set.add(k)
else:
yield element
except TypeError:
if k not in seen_list:
seen_list.append(k)
else:
yield element
def duplicates_justseen(iterable, key=None):
"""Yields serially-duplicate elements after their first appearance.
>>> list(duplicates_justseen('mississippi'))
['s', 's', 'p']
>>> list(duplicates_justseen('AaaBbbCccAaa', str.lower))
['a', 'a', 'b', 'b', 'c', 'c', 'a', 'a']
This function is analagous to :func:`unique_justseen`.
"""
return flatten(
map(
lambda group_tuple: islice_extended(group_tuple[1])[1:],
groupby(iterable, key),
)
)
def minmax(iterable_or_value, *others, key=None, default=_marker):
"""Returns both the smallest and largest items in an iterable
or the largest of two or more arguments.
>>> minmax([3, 1, 5])
(1, 5)
>>> minmax(4, 2, 6)
(2, 6)
If a *key* function is provided, it will be used to transform the input
items for comparison.
>>> minmax([5, 30], key=str) # '30' sorts before '5'
(30, 5)
If a *default* value is provided, it will be returned if there are no
input items.
>>> minmax([], default=(0, 0))
(0, 0)
Otherwise ``ValueError`` is raised.
This function is based on the
`recipe <http://code.activestate.com/recipes/577916/>`__ by
Raymond Hettinger and takes care to minimize the number of comparisons
performed.
"""
iterable = (iterable_or_value, *others) if others else iterable_or_value
it = iter(iterable)
try:
lo = hi = next(it)
except StopIteration as e:
if default is _marker:
raise ValueError(
'`minmax()` argument is an empty iterable. '
'Provide a `default` value to suppress this error.'
) from e
return default
# Different branches depending on the presence of key. This saves a lot
# of unimportant copies which would slow the "key=None" branch
# significantly down.
if key is None:
for x, y in zip_longest(it, it, fillvalue=lo):
if y < x:
x, y = y, x
if x < lo:
lo = x
if hi < y:
hi = y
else:
lo_key = hi_key = key(lo)
for x, y in zip_longest(it, it, fillvalue=lo):
x_key, y_key = key(x), key(y)
if y_key < x_key:
x, y, x_key, y_key = y, x, y_key, x_key
if x_key < lo_key:
lo, lo_key = x, x_key
if hi_key < y_key:
hi, hi_key = y, y_key
return lo, hi
def constrained_batches(
iterable, max_size, max_count=None, get_len=len, strict=True
):
"""Yield batches of items from *iterable* with a combined size limited by
*max_size*.
>>> iterable = [b'12345', b'123', b'12345678', b'1', b'1', b'12', b'1']
>>> list(constrained_batches(iterable, 10))
[(b'12345', b'123'), (b'12345678', b'1', b'1'), (b'12', b'1')]
If a *max_count* is supplied, the number of items per batch is also
limited:
>>> iterable = [b'12345', b'123', b'12345678', b'1', b'1', b'12', b'1']
>>> list(constrained_batches(iterable, 10, max_count = 2))
[(b'12345', b'123'), (b'12345678', b'1'), (b'1', b'12'), (b'1',)]
If a *get_len* function is supplied, use that instead of :func:`len` to
determine item size.
If *strict* is ``True``, raise ``ValueError`` if any single item is bigger
than *max_size*. Otherwise, allow single items to exceed *max_size*.
"""
if max_size <= 0:
raise ValueError('maximum size must be greater than zero')
batch = []
batch_size = 0
batch_count = 0
for item in iterable:
item_len = get_len(item)
if strict and item_len > max_size:
raise ValueError('item size exceeds maximum size')
reached_count = batch_count == max_count
reached_size = item_len + batch_size > max_size
if batch_count and (reached_size or reached_count):
yield tuple(batch)
batch.clear()
batch_size = 0
batch_count = 0
batch.append(item)
batch_size += item_len
batch_count += 1
if batch:
yield tuple(batch)
| mit | fc296c9c995af0b86bdc87917048b495 | 29.671419 | 79 | 0.55385 | 3.756618 | false | false | false | false |
twisted/axiom | axiom/_fincache.py | 1 | 5354 | from weakref import ref
from traceback import print_exc
from twisted.python import log
from axiom import iaxiom
class CacheFault(KeyError):
"""
An item has fallen out of cache, but the weakref callback has not yet run.
"""
class CacheInconsistency(RuntimeError):
"""
A key being cached is already present in the cache.
"""
def logErrorNoMatterWhat():
try:
log.msg("Exception in finalizer cannot be propagated")
log.err()
except:
try:
emergLog = file("WEAKREF_EMERGENCY_ERROR.log", 'a')
print_exc(file=emergLog)
emergLog.flush()
emergLog.close()
except:
# Nothing can be done. We can't get an emergency log file to write
# to. Don't bother.
return
def createCacheRemoveCallback(cacheRef, key, finalizer):
"""
Construct a callable to be used as a weakref callback for cache entries.
The callable will invoke the provided finalizer, as well as removing the
cache entry if the cache still exists and contains an entry for the given
key.
@type cacheRef: L{weakref.ref} to L{FinalizingCache}
@param cacheRef: A weakref to the cache in which the corresponding cache
item was stored.
@param key: The key for which this value is cached.
@type finalizer: callable taking 0 arguments
@param finalizer: A user-provided callable that will be called when the
weakref callback runs.
"""
def remove(reference):
# Weakref callbacks cannot raise exceptions or DOOM ensues
try:
finalizer()
except:
logErrorNoMatterWhat()
try:
cache = cacheRef()
if cache is not None:
if key in cache.data:
if cache.data[key] is reference:
del cache.data[key]
except:
logErrorNoMatterWhat()
return remove
class FinalizingCache:
"""
A cache that stores values by weakref.
A finalizer is invoked when the weakref to a cached value is broken.
@type data: L{dict}
@ivar data: The cached values.
"""
def __init__(self, _ref=ref):
self.data = {}
self._ref = _ref
def cache(self, key, value):
"""
Add an entry to the cache.
A weakref to the value is stored, rather than a direct reference. The
value must have a C{__finalizer__} method that returns a callable which
will be invoked when the weakref is broken.
@param key: The key identifying the cache entry.
@param value: The value for the cache entry.
"""
fin = value.__finalizer__()
try:
# It's okay if there's already a cache entry for this key as long
# as the weakref has already been broken. See the comment in
# get() for an explanation of why this might happen.
if self.data[key]() is not None:
raise CacheInconsistency(
"Duplicate cache key: {!r} {!r} {!r}".format(
key, value, self.data[key]))
except KeyError:
pass
callback = createCacheRemoveCallback(self._ref(self), key, fin)
self.data[key] = self._ref(value, callback)
return value
def uncache(self, key, value):
"""
Remove a key from the cache.
As a sanity check, if the specified key is present in the cache, it
must have the given value.
@param key: The key to remove.
@param value: The expected value for the key.
"""
try:
assert self.get(key) is value
del self.data[key]
except KeyError:
# If the entry has already been removed from the cache, this will
# result in KeyError which we ignore. If the entry is still in the
# cache, but the weakref has been broken, this will result in
# CacheFault (a KeyError subclass) which we also ignore. See the
# comment in get() for an explanation of why this might happen.
pass
def get(self, key):
"""
Get an entry from the cache by key.
@raise KeyError: if the given key is not present in the cache.
@raise CacheFault: (a L{KeyError} subclass) if the given key is present
in the cache, but the value it points to is gone.
"""
o = self.data[key]()
if o is None:
# On CPython, the weakref callback will always(?) run before any
# other code has a chance to observe that the weakref is broken;
# and since the callback removes the item from the dict, this
# branch of code should never run. However, on PyPy (and possibly
# other Python implementations), the weakref callback does not run
# immediately, thus we may be able to observe this intermediate
# state. Should this occur, we remove the dict item ourselves,
# and raise CacheFault (which is a KeyError subclass).
del self.data[key]
raise CacheFault(
"FinalizingCache has {!r} but its value is no more.".format(key))
log.msg(interface=iaxiom.IStatEvent, stat_cache_hits=1, key=key)
return o
| mit | 269a9b6b5d3f29ea2c295033be0571ec | 31.646341 | 81 | 0.600486 | 4.417492 | false | false | false | false |
twisted/axiom | axiom/upgrade.py | 1 | 11403 | # -*- test-case-name: axiom.test.test_upgrading -*-
"""
Axiom Item/schema upgrade support.
"""
from twisted.python.failure import Failure
from twisted.python.log import msg
from twisted.python.reflect import qual
from axiom.errors import NoUpgradePathAvailable, UpgraderRecursion
from axiom.errors import ItemUpgradeError
from axiom.item import _legacyTypes, _typeNameToMostRecentClass
from axiom._schema import (
CREATE_OBJECTS, CREATE_OBJECTS_IDX, CREATE_TYPES, LATEST_TYPES)
_upgradeRegistry = {}
class _StoreUpgrade(object):
"""
Manage Item upgrades and upgrade batching for a store.
@type _currentlyUpgrading: C{dict}
@ivar _currentlyUpgrading: A map of storeIDs to Items currently in the
middle of an upgrader. Used to make sure that the same item isn't
upgraded reentrantly.
@type _oldTypesRemaining: C{list}
@ivar _oldTypesRemaining: All the old types which have not been fully
upgraded in this database.
"""
def __init__(self, store):
self.store = store
self._currentlyUpgrading = {}
self._oldTypesRemaining = []
def upgradesPending(self):
return bool(self._oldTypesRemaining)
upgradesPending = property(
upgradesPending,
doc="""
Flag indicating whether there any types that still need to be upgraded
or not.
""")
def checkUpgradePaths(self):
"""
Check that all of the accumulated old Item types have a way to get
from their current version to the latest version.
@raise axiom.errors.NoUpgradePathAvailable: for any, and all, Items
that do not have a valid upgrade path
"""
cantUpgradeErrors = []
for oldVersion in self._oldTypesRemaining:
# We have to be able to get from oldVersion.schemaVersion to
# the most recent type.
currentType = _typeNameToMostRecentClass.get(
oldVersion.typeName, None)
if currentType is None:
# There isn't a current version of this type; it's entirely
# legacy, will be upgraded by deleting and replacing with
# something else.
continue
typeInQuestion = oldVersion.typeName
upgver = oldVersion.schemaVersion
while upgver < currentType.schemaVersion:
# Do we have enough of the schema present to upgrade?
if ((typeInQuestion, upgver)
not in _upgradeRegistry):
cantUpgradeErrors.append(
"No upgrader present for %s (%s) from %d to %d" % (
typeInQuestion, qual(currentType), upgver,
upgver + 1))
# Is there a type available for each upgrader version?
if upgver+1 != currentType.schemaVersion:
if (typeInQuestion, upgver+1) not in _legacyTypes:
cantUpgradeErrors.append(
"Type schema required for upgrade missing:"
" %s version %d" % (
typeInQuestion, upgver+1))
upgver += 1
if cantUpgradeErrors:
raise NoUpgradePathAvailable('\n '.join(cantUpgradeErrors))
def queueTypeUpgrade(self, oldtype):
"""
Queue a type upgrade for C{oldtype}.
"""
if oldtype not in self._oldTypesRemaining:
self._oldTypesRemaining.append(oldtype)
def upgradeItem(self, thisItem):
"""
Upgrade a legacy item.
@raise axiom.errors.UpgraderRecursion: If the given item is already in
the process of being upgraded.
"""
sid = thisItem.storeID
if sid in self._currentlyUpgrading:
raise UpgraderRecursion()
self._currentlyUpgrading[sid] = thisItem
try:
return upgradeAllTheWay(thisItem)
finally:
self._currentlyUpgrading.pop(sid)
def upgradeEverything(self):
"""
Upgrade every item in the store, one at a time.
@raise axiom.errors.ItemUpgradeError: if an item upgrade failed
@return: A generator that yields for each item upgrade.
"""
return self.upgradeBatch(1)
def upgradeBatch(self, n):
"""
Upgrade the entire store in batches, yielding after each batch.
@param n: Number of upgrades to perform per transaction
@type n: C{int}
@raise axiom.errors.ItemUpgradeError: if an item upgrade failed
@return: A generator that yields after each batch upgrade. This needs
to be consumed for upgrading to actually take place.
"""
store = self.store
def _doBatch(itemType):
upgradedAnything = False
for theItem in store.query(itemType, limit=n):
upgradedAnything = True
try:
self.upgradeItem(theItem)
except:
f = Failure()
raise ItemUpgradeError(
f, theItem.storeID, itemType,
_typeNameToMostRecentClass[itemType.typeName])
return upgradedAnything
if self.upgradesPending:
didAny = False
while self._oldTypesRemaining:
t0 = self._oldTypesRemaining[0]
upgradedAnything = store.transact(_doBatch, t0)
if not upgradedAnything:
self._oldTypesRemaining.pop(0)
if didAny:
msg("{} finished upgrading {}".format(store.dbdir.path, qual(t0)))
continue
elif not didAny:
didAny = True
msg("{} beginning upgrade...".format(store.dbdir.path))
yield None
if didAny:
msg("{} completely upgraded.".format(store.dbdir.path))
def registerUpgrader(upgrader, typeName, oldVersion, newVersion):
"""
Register a callable which can perform a schema upgrade between two
particular versions.
@param upgrader: A one-argument callable which will upgrade an object. It
is invoked with an instance of the old version of the object.
@param typeName: The database typename for which this is an upgrader.
@param oldVersion: The version from which this will upgrade.
@param newVersion: The version to which this will upgrade. This must be
exactly one greater than C{oldVersion}.
"""
# assert (typeName, oldVersion, newVersion) not in _upgradeRegistry, "duplicate upgrader"
# ^ this makes the tests blow up so it's just disabled for now; perhaps we
# should have a specific test mode
# assert newVersion - oldVersion == 1, "read the doc string"
assert isinstance(typeName, str), "read the doc string"
_upgradeRegistry[typeName, oldVersion] = upgrader
def registerAttributeCopyingUpgrader(itemType, fromVersion, toVersion, postCopy=None):
"""
Register an upgrader for C{itemType}, from C{fromVersion} to C{toVersion},
which will copy all attributes from the legacy item to the new item. If
postCopy is provided, it will be called with the new item after upgrading.
@param itemType: L{axiom.item.Item} subclass
@param postCopy: a callable of one argument
@return: None
"""
def upgrader(old):
newitem = old.upgradeVersion(itemType.typeName, fromVersion, toVersion,
**{str(name): getattr(old, name)
for (name, _) in old.getSchema()})
if postCopy is not None:
postCopy(newitem)
return newitem
registerUpgrader(upgrader, itemType.typeName, fromVersion, toVersion)
def registerDeletionUpgrader(itemType, fromVersion, toVersion):
"""
Register an upgrader for C{itemType}, from C{fromVersion} to C{toVersion},
which will delete the item from the database.
@param itemType: L{axiom.item.Item} subclass
@return: None
"""
# XXX This should actually do something more special so that a new table is
# not created and such.
def upgrader(old):
old.deleteFromStore()
return None
registerUpgrader(upgrader, itemType.typeName, fromVersion, toVersion)
def upgradeAllTheWay(o):
assert o.__legacy__
while True:
try:
upgrader = _upgradeRegistry[o.typeName, o.schemaVersion]
except KeyError:
break
else:
o = upgrader(o)
if o is None:
# Object was explicitly destroyed during upgrading.
break
return o
def _hasExplicitOid(store, table):
"""
Does the given table have an explicit oid column?
"""
return any(info[1] == 'oid' for info
in store.querySchemaSQL(
'PRAGMA *DATABASE*.table_info({})'.format(table)))
def _upgradeTableOid(store, table, createTable, postCreate=lambda: None):
"""
Upgrade a table to have an explicit oid.
Must be called in a transaction to avoid corrupting the database.
"""
if _hasExplicitOid(store, table):
return
store.executeSchemaSQL(
'ALTER TABLE *DATABASE*.{0} RENAME TO {0}_temp'.format(table))
createTable()
store.executeSchemaSQL(
'INSERT INTO *DATABASE*.{0} '
'SELECT oid, * FROM *DATABASE*.{0}_temp'.format(table))
store.executeSchemaSQL('DROP TABLE *DATABASE*.{}_temp'.format(table))
postCreate()
def upgradeSystemOid(store):
"""
Upgrade the system tables to use explicit oid columns.
"""
store.transact(
_upgradeTableOid, store, 'axiom_types',
lambda: store.executeSchemaSQL(CREATE_TYPES))
store.transact(
_upgradeTableOid, store, 'axiom_objects',
lambda: store.executeSchemaSQL(CREATE_OBJECTS),
lambda: store.executeSchemaSQL(CREATE_OBJECTS_IDX))
def upgradeExplicitOid(store):
"""
Upgrade a store to use explicit oid columns.
This allows VACUUMing the database without corrupting it.
This requires copying all of axiom_objects and axiom_types, as well as all
item tables that have not yet been upgraded. Consider VACUUMing the
database afterwards to reclaim space.
"""
upgradeSystemOid(store)
for typename, version in store.querySchemaSQL(LATEST_TYPES):
cls = _typeNameToMostRecentClass[typename]
if cls.schemaVersion != version:
remaining = store.querySQL(
'SELECT oid FROM {} LIMIT 1'.format(
store._tableNameFor(typename, version)))
if len(remaining) == 0:
# Nothing to upgrade
continue
else:
raise RuntimeError(
'{}:{} not fully upgraded to {}'.format(
typename, version, cls.schemaVersion))
store.transact(
_upgradeTableOid,
store,
store._tableNameOnlyFor(typename, version),
lambda: store._justCreateTable(cls),
lambda: store._createIndexesFor(cls, []))
__all__ = [
'registerUpgrader', 'registerAttributeCopyingUpgrader',
'registerDeletionUpgrader', 'upgradeExplicitOid']
| mit | 8414fe1b5daecdac39065aeca456ac7b | 32.9375 | 93 | 0.610103 | 4.360612 | false | false | false | false |
twisted/axiom | axiom/tags.py | 2 | 3742 |
from epsilon.extime import Time
from axiom.item import Item
from axiom.attributes import text, reference, integer, AND, timestamp
class Tag(Item):
typeName = 'tag'
schemaVersion = 1
name = text(doc="""
The short string which is being applied as a tag to an Item.
""")
created = timestamp(doc="""
When this tag was applied to the Item to which it applies.
""")
object = reference(doc="""
The Item to which this tag applies.
""")
catalog = reference(doc="""
The L{Catalog} item in which this tag was created.
""")
tagger = reference(doc="""
An optional reference to the Item which is responsible for this tag's
existence.
""")
class _TagName(Item):
"""
Helper class to make Catalog.tagNames very fast. One of these is created
for each distinct tag name that is created. _TagName Items are never
deleted from the database.
"""
typeName = 'tagname'
name = text(doc="""
The short string which uniquely represents this tag.
""", indexed=True)
catalog = reference(doc="""
The L{Catalog} item in which this tag exists.
""")
class Catalog(Item):
typeName = 'tag_catalog'
schemaVersion = 2
tagCount = integer(default=0)
def tag(self, obj, tagName, tagger=None):
"""
"""
# check to see if that tag exists. Put the object attribute first,
# since each object should only have a handful of tags and the object
# reference is indexed. As long as this is the case, it doesn't matter
# whether the name or catalog attributes are indexed because selecting
# from a small set of results is fast even without an index.
if self.store.findFirst(Tag,
AND(Tag.object == obj,
Tag.name == tagName,
Tag.catalog == self)):
return
# if the tag doesn't exist, maybe we need to create a new tagname object
self.store.findOrCreate(_TagName, name=tagName, catalog=self)
# Increment only if we are creating a new tag
self.tagCount += 1
Tag(store=self.store, object=obj,
name=tagName, catalog=self,
created=Time(), tagger=tagger)
def tagNames(self):
"""
Return an iterator of unicode strings - the unique tag names which have
been applied objects in this catalog.
"""
return self.store.query(_TagName, _TagName.catalog == self).getColumn("name")
def tagsOf(self, obj):
"""
Return an iterator of unicode strings - the tag names which apply to
the given object.
"""
return self.store.query(
Tag,
AND(Tag.catalog == self,
Tag.object == obj)).getColumn("name")
def objectsIn(self, tagName):
return self.store.query(
Tag,
AND(Tag.catalog == self,
Tag.name == tagName)).getColumn("object")
def upgradeCatalog1to2(oldCatalog):
"""
Create _TagName instances which version 2 of Catalog automatically creates
for use in determining the tagNames result, but which version 1 of Catalog
did not create.
"""
newCatalog = oldCatalog.upgradeVersion('tag_catalog', 1, 2,
tagCount=oldCatalog.tagCount)
tags = newCatalog.store.query(Tag, Tag.catalog == newCatalog)
tagNames = tags.getColumn("name").distinct()
for t in tagNames:
_TagName(store=newCatalog.store, catalog=newCatalog, name=t)
return newCatalog
from axiom.upgrade import registerUpgrader
registerUpgrader(upgradeCatalog1to2, 'tag_catalog', 1, 2)
| mit | 63776f992967b0e0e73e9152559ed653 | 28.936 | 85 | 0.611972 | 4.331019 | false | false | false | false |
twisted/axiom | axiom/plugins/axiom_plugins.py | 1 | 9700 | # Copyright (c) 2008 Divmod. See LICENSE for details.
"""
Plugins provided by Axiom for Axiom.
"""
from __future__ import print_function
import getpass
import code, os, traceback, sys
try:
import readline
except ImportError:
readline = None
from zope.interface import directlyProvides
from twisted.python import usage, filepath, log
from twisted.python.reflect import qual
from twisted.plugin import IPlugin
import axiom
from axiom import store, attributes, userbase, dependency, errors
from axiom.substore import SubStore
from axiom.scripts import axiomatic
from axiom.listversions import ListVersions
from axiom import version
from axiom.iaxiom import IVersion
from axiom.upgrade import upgradeExplicitOid
directlyProvides(version, IPlugin, IVersion)
#placate pyflakes
ListVersions
class Upgrade(axiomatic.AxiomaticCommand):
name = 'upgrade'
description = 'Synchronously upgrade an Axiom store and substores'
optParameters = [
('count', 'n', '100', 'Number of upgrades to perform per transaction')]
errorMessageFormat = 'Error upgrading item (with typeName=%s and storeID=%d) from version %d to %d.'
def upgradeEverything(self, store):
"""
Upgrade all the items in C{store}.
"""
for dummy in store._upgradeManager.upgradeBatch(self.count):
pass
def upgradeStore(self, store):
"""
Recursively upgrade C{store}.
"""
self.upgradeEverything(store)
upgradeExplicitOid(store)
for substore in store.query(SubStore):
print(u'Upgrading: {!r}'.format(substore))
self.upgradeStore(substore.open())
def perform(self, store, count):
"""
Upgrade C{store} performing C{count} upgrades per transaction.
Also, catch any exceptions and print out something useful.
"""
self.count = count
try:
self.upgradeStore(store)
print(u'Upgrade complete')
except errors.ItemUpgradeError as e:
print(u'Upgrader error:')
e.originalFailure.printTraceback(file=sys.stdout)
print(self.errorMessageFormat % (
e.oldType.typeName, e.storeID, e.oldType.schemaVersion,
e.newType.schemaVersion))
def postOptions(self):
try:
count = int(self['count'])
except ValueError:
raise usage.UsageError('count must be an integer')
siteStore = self.parent.getStore()
self.perform(siteStore, count)
class AxiomConsole(code.InteractiveConsole):
def runcode(self, code):
"""
Override L{code.InteractiveConsole.runcode} to run the code in a
transaction unless the local C{autocommit} is currently set to a true
value.
"""
if not self.locals.get('autocommit', None):
return self.locals['db'].transact(code.InteractiveConsole.runcode, self, code)
return code.InteractiveConsole.runcode(self, code)
class Browse(axiomatic.AxiomaticCommand):
synopsis = "[options]"
name = 'browse'
description = 'Interact with an Axiom store.'
optParameters = [
('history-file', 'h', '~/.axiomatic-browser-history',
'Name of the file to which to save input history.'),
]
optFlags = [
('debug', 'b', 'Open Store in debug mode.'),
]
def postOptions(self):
interp = code.InteractiveConsole(self.namespace(), '<axiom browser>')
historyFile = os.path.expanduser(self['history-file'])
if readline is not None and os.path.exists(historyFile):
readline.read_history_file(historyFile)
try:
interp.interact("%s. Autocommit is off." % (str(axiom.version),))
finally:
if readline is not None:
readline.write_history_file(historyFile)
def namespace(self):
"""
Return a dictionary representing the namespace which should be
available to the user.
"""
self._ns = {
'db': self.store,
'store': store,
'autocommit': False,
}
return self._ns
class UserbaseMixin:
def installOn(self, other):
# XXX check installation on other, not store
for ls in self.store.query(userbase.LoginSystem):
raise usage.UsageError("UserBase already installed")
else:
ls = userbase.LoginSystem(store=self.store)
dependency.installOn(ls, other)
return ls
class Install(axiomatic.AxiomaticSubCommand, UserbaseMixin):
def postOptions(self):
self.installOn(self.store)
class Create(axiomatic.AxiomaticSubCommand, UserbaseMixin):
synopsis = "<username> <domain> [password]"
def parseArgs(self, username, domain, password=None):
self['username'] = self.decodeCommandLine(username)
self['domain'] = self.decodeCommandLine(domain)
self['password'] = password
def postOptions(self):
msg = 'Enter new AXIOM password: '
while not self['password']:
password = getpass.getpass(msg)
second = getpass.getpass('Repeat to verify: ')
if password == second:
self['password'] = password
else:
msg = 'Passwords do not match. Enter new AXIOM password: '
self.addAccount(
self.store, self['username'], self['domain'], self['password'])
def addAccount(self, siteStore, username, domain, password):
"""
Create a new account in the given store.
@param siteStore: A site Store to which login credentials will be
added.
@param username: Local part of the username for the credentials to add.
@param domain: Domain part of the username for the credentials to add.
@param password: Password for the credentials to add.
@rtype: L{LoginAccount}
@return: The added account.
"""
for ls in siteStore.query(userbase.LoginSystem):
break
else:
ls = self.installOn(siteStore)
try:
acc = ls.addAccount(username, domain, password)
except userbase.DuplicateUser:
raise usage.UsageError("An account by that name already exists.")
return acc
class Disable(axiomatic.AxiomaticSubCommand):
synopsis = "<username> <domain>"
def parseArgs(self, username, domain):
self['username'] = self.decodeCommandLine(username)
self['domain'] = self.decodeCommandLine(domain)
def postOptions(self):
for acc in self.store.query(userbase.LoginAccount,
attributes.AND(userbase.LoginAccount.username == self['username'],
userbase.LoginAccount.domain == self['domain'])):
if acc.disabled:
raise usage.UsageError("That account is already disabled.")
else:
acc.disabled = True
break
else:
raise usage.UsageError("No account by that name exists.")
class List(axiomatic.AxiomaticSubCommand):
def postOptions(self):
acc = None
for acc in self.store.query(userbase.LoginMethod):
if acc.domain is None:
print(acc.localpart, end=u'')
else:
print(acc.localpart + u'@' + acc.domain, end=u'')
if acc.account.disabled:
print(u' [DISABLED]')
else:
print(u'')
if acc is None:
print(u'No accounts')
class UserBaseCommand(axiomatic.AxiomaticCommand):
name = 'userbase'
description = 'LoginSystem introspection and manipulation.'
subCommands = [
('install', None, Install, "Install UserBase on an Axiom database"),
('create', None, Create, "Create a new user"),
('disable', None, Disable, "Disable an existing user"),
('list', None, List, "List users in an Axiom database"),
]
def getStore(self):
return self.parent.getStore()
class Extract(axiomatic.AxiomaticCommand):
name = 'extract-user'
description = 'Remove an account from the login system, moving its associated database to the filesystem.'
optParameters = [
('address', 'a', None, 'localpart@domain-format identifier of the user store to extract.'),
('destination', 'd', None, 'Directory into which to extract the user store.')]
def extractSubStore(self, localpart, domain, destinationPath):
siteStore = self.parent.getStore()
la = siteStore.findFirst(
userbase.LoginMethod,
attributes.AND(userbase.LoginMethod.localpart == localpart,
userbase.LoginMethod.domain == domain)).account
userbase.extractUserStore(la, destinationPath)
def postOptions(self):
localpart, domain = self.decodeCommandLine(self['address']).split('@', 1)
destinationPath = filepath.FilePath(
self.decodeCommandLine(self['destination'])).child(localpart + '@' + domain + '.axiom')
self.extractSubStore(localpart, domain, destinationPath)
class Insert(axiomatic.AxiomaticCommand):
name = 'insert-user'
description = 'Insert a user store, such as one extracted with "extract-user", into a site store and login system.'
optParameters = [
('userstore', 'u', None, 'Path to user store to be inserted.')
]
def postOptions(self):
userbase.insertUserStore(self.parent.getStore(),
filepath.FilePath(self.decodeCommandLine(self['userstore'])))
| mit | 63245d3483a71640f340183ac1d4b129 | 31.333333 | 119 | 0.623711 | 4.248795 | false | false | false | false |
twisted/axiom | axiom/test/test_reference.py | 1 | 8741 | import gc
from twisted.trial.unittest import TestCase
from axiom.store import Store
from axiom.upgrade import registerUpgrader, registerAttributeCopyingUpgrader
from axiom.item import Item, declareLegacyItem
from axiom.attributes import integer, reference
from axiom.errors import BrokenReference, DeletionDisallowed
class Referee(Item):
schemaVersion = 1
typeName = "test_reference_referee"
topSecret = integer()
class SimpleReferent(Item):
schemaVersion = 1
typeName = "test_reference_referent"
ref = reference()
class BreakingReferent(Item):
schemaVersion = 1
typeName = "test_reference_breaking_referent"
ref = reference(whenDeleted=reference.NULLIFY)
class DependentReferent(Item):
ref = reference(whenDeleted=reference.CASCADE, reftype=Referee)
class DisallowReferent(Item):
ref = reference(whenDeleted=reference.DISALLOW, reftype=Referee)
class BadReferenceTestCase(TestCase):
ntimes = 10
def testSanity(self):
store = Store()
for i in range(self.ntimes):
SimpleReferent(store=store, ref=Referee(store=store, topSecret=i))
(referee,) = list(store.query(Referee))
(referent,) = list(store.query(SimpleReferent))
self.assertEqual(referent.ref.topSecret, referee.topSecret)
referee.deleteFromStore()
referent.deleteFromStore()
def testBadReferenceNone(self):
"""
Test that accessing a broken reference on an Item that has already been
loaded into memory correctly nullifies the attribute.
"""
store = Store()
referee = Referee(store=store, topSecret=0)
referent = SimpleReferent(store=store, ref=referee)
referee.deleteFromStore()
referee = None
gc.collect()
(referent,) = list(store.query(SimpleReferent))
self.assertEqual(referent.ref, None)
def testBadReferenceNoneLoading(self):
"""
Test that accessing a broken reference on an Item that has not yet been
loaded correctly nullifies the attribute.
"""
store = Store()
referee = Referee(store=store, topSecret=0)
referent = SimpleReferent(store=store, ref=referee)
referee.deleteFromStore()
referee = None
referent = None
gc.collect()
(referent,) = list(store.query(SimpleReferent))
self.assertEqual(referent.ref, None)
def test_brokenReferenceException(self):
"""
Test that an exception is raised when a broken reference is detected
when this should be impossible (ie. CASCADE or NULLIFY).
"""
store = Store()
referee = Referee(store=store, topSecret=0)
referent = BreakingReferent(store=store, ref=referee)
referee.deleteFromStore()
referent = None
gc.collect()
referent = store.findFirst(BreakingReferent)
self.patch(BreakingReferent.ref, 'whenDeleted', reference.CASCADE)
self.assertRaises(BrokenReference, lambda: referent.ref)
def testBadReferenceNoneRevert(self):
store = Store()
referee = Referee(store=store, topSecret=0)
referent = SimpleReferent(store=store, ref=referee)
def txn():
referee.deleteFromStore()
self.assertEqual(referent.ref, None)
1 / 0
self.assertRaises(ZeroDivisionError, store.transact, txn)
self.assertEqual(referent.ref, referee)
referent = None
referee = None
gc.collect()
referent = store.findUnique(SimpleReferent)
referee = store.findUnique(Referee)
self.assertEqual(referent.ref, referee)
def testBrokenReferenceDisallow(self):
"""
Test that deleting an item referred to by a whenDeleted == DISALLOW
reference raises an exception.
"""
store = Store()
referee = Referee(store=store, topSecret=0)
referent = DisallowReferent(store=store, ref=referee)
self.assertRaises(DeletionDisallowed, referee.deleteFromStore)
self.assertRaises(DeletionDisallowed, store.query(Referee).deleteFromStore)
def testReferenceQuery(self):
store = Store()
referee = Referee(store=store, topSecret=0)
self.assertEqual(
list(store.query(SimpleReferent,
SimpleReferent.ref == Referee.storeID)),
[])
def testReferenceDeletion(self):
store = Store()
referee = Referee(store=store, topSecret=0)
dep = DependentReferent(store=store,
ref=referee)
sid = dep.storeID
self.assertIdentical(store.getItemByID(sid), dep) # sanity
referee.deleteFromStore()
self.assertRaises(KeyError, store.getItemByID, sid)
def testBatchReferenceDeletion(self):
"""
Test that batch deletion removes dependent items correctly.
"""
store = Store()
referee = Referee(store=store, topSecret=0)
dep = DependentReferent(store=store,
ref=referee)
sid = dep.storeID
store.query(Referee).deleteFromStore()
self.assertRaises(KeyError, store.getItemByID, sid)
def test_dummyItemReference(self):
"""
Getting the value of a reference attribute which has previously been
set to a legacy item results in an instance of the most recent type for
that item.
"""
store = Store()
referent = SimpleReferent(store=store)
oldReferee = nonUpgradedItem(store=store)
referent.ref = oldReferee
newReferee = referent.ref
self.assertTrue(
isinstance(newReferee, UpgradedItem),
"{!r} was instance of {!r}, expected {!r}".format(newReferee,
type(newReferee),
UpgradedItem))
def test_dummyItemReferenceUpgraded(self):
"""
Getting the value of a reference attribute which has been set to a
legacy item, which is then upgraded while the reference is "live",
results in an instance of the most recent type for that item.
"""
store = Store()
referent = SimpleReferent(store=store)
oldReferee = nonUpgradedItem2(store=store)
referent.ref = oldReferee
# Manually run the upgrader on this specific legacy item. This is the
# same as if the SimpleReferent item had been created in an upgrader
# for UpgradedItem, except that we can keep a strong reference to
# oldReferee to ensure it is not garbage collected (this would
# otherwise happen nondeterministically on platforms like PyPy).
newReferee = item2to3(oldReferee)
self.assertIsInstance(newReferee, UpgradedItem)
self.assertIdentical(referent.ref, newReferee)
def test_dummyItemReferenceInUpgrade(self):
"""
Setting the value of a reference attribute to a legacy item during an
upgrade results in the same value being set on the upgraded item.
"""
store = Store()
def tx():
oldReferent = nonUpgradedItem(store=store)
oldReferee = nonUpgradedItem(store=store)
newReferent = oldReferent.upgradeVersion(
UpgradedItem.typeName, 1, 2)
newReferee = oldReferee.upgradeVersion(
UpgradedItem.typeName, 1, 2, ref=newReferent)
self.assertIdentical(newReferee.ref, newReferent)
store.transact(tx)
def test_dummyItemGetItemByID(self):
"""
Instantiating a dummy item and then getting it by its storeID should
upgrade it.
"""
store = Store()
t = nonUpgradedItem(store=store)
self.assertEqual(t.__legacy__, True)
self.assertRaises(KeyError, store.objectCache.get, t.storeID)
t2 = store.getItemByID(t.storeID)
self.assertNotIdentical(t, t2)
self.assertTrue(isinstance(t2, UpgradedItem))
class UpgradedItem(Item):
"""
A simple item which is the current version of L{nonUpgradedItem}.
"""
schemaVersion = 3
ref = reference()
nonUpgradedItem = declareLegacyItem(
UpgradedItem.typeName, 1,
dict(ref=reference()))
nonUpgradedItem2 = declareLegacyItem(
UpgradedItem.typeName, 2,
dict(ref=reference()))
registerAttributeCopyingUpgrader(UpgradedItem, 1, 2)
def item2to3(old):
"""
Upgrade an nonUpgradedItem to UpgradedItem
"""
return old.upgradeVersion(UpgradedItem.typeName, 2, 3, ref=old.ref)
registerUpgrader(item2to3, UpgradedItem.typeName, 2, 3)
| mit | e7a6cfaaa85a924aeac9b79e0287e095 | 32.362595 | 83 | 0.644091 | 3.886616 | false | true | false | false |
amueller/word_cloud | examples/wordcloud_cn.py | 1 | 3059 | # - * - coding: utf - 8 -*-
"""
create wordcloud with chinese
=============================
Wordcloud is a very good tool, but if you want to create
Chinese wordcloud only wordcloud is not enough. The file
shows how to use wordcloud with Chinese. First, you need a
Chinese word segmentation library jieba, jieba is now the
most elegant the most popular Chinese word segmentation tool in python.
You can use 'PIP install jieba'. To install it. As you can see,
at the same time using wordcloud with jieba very convenient
"""
import jieba
jieba.enable_parallel(4)
# Setting up parallel processes :4 ,but unable to run on Windows
from os import path
from imageio import imread
import matplotlib.pyplot as plt
import os
# jieba.load_userdict("txt\userdict.txt")
# add userdict by load_userdict()
from wordcloud import WordCloud, ImageColorGenerator
# get data directory (using getcwd() is needed to support running example in generated IPython notebook)
d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()
stopwords_path = d + '/wc_cn/stopwords_cn_en.txt'
# Chinese fonts must be set
font_path = d + '/fonts/SourceHanSerif/SourceHanSerifK-Light.otf'
# the path to save worldcloud
imgname1 = d + '/wc_cn/LuXun.jpg'
imgname2 = d + '/wc_cn/LuXun_colored.jpg'
# read the mask / color image taken from
back_coloring = imread(path.join(d, d + '/wc_cn/LuXun_color.jpg'))
# Read the whole text.
text = open(path.join(d, d + '/wc_cn/CalltoArms.txt')).read()
# if you want use wordCloud,you need it
# add userdict by add_word()
userdict_list = ['阿Q', '孔乙己', '单四嫂子']
# The function for processing text with Jieba
def jieba_processing_txt(text):
for word in userdict_list:
jieba.add_word(word)
mywordlist = []
seg_list = jieba.cut(text, cut_all=False)
liststr = "/ ".join(seg_list)
with open(stopwords_path, encoding='utf-8') as f_stop:
f_stop_text = f_stop.read()
f_stop_seg_list = f_stop_text.splitlines()
for myword in liststr.split('/'):
if not (myword.strip() in f_stop_seg_list) and len(myword.strip()) > 1:
mywordlist.append(myword)
return ' '.join(mywordlist)
wc = WordCloud(font_path=font_path, background_color="white", max_words=2000, mask=back_coloring,
max_font_size=100, random_state=42, width=1000, height=860, margin=2,)
wc.generate(jieba_processing_txt(text))
# create coloring from image
image_colors_default = ImageColorGenerator(back_coloring)
plt.figure()
# recolor wordcloud and show
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()
# save wordcloud
wc.to_file(path.join(d, imgname1))
# create coloring from image
image_colors_byImg = ImageColorGenerator(back_coloring)
# show
# we could also give color_func=image_colors directly in the constructor
plt.imshow(wc.recolor(color_func=image_colors_byImg), interpolation="bilinear")
plt.axis("off")
plt.figure()
plt.imshow(back_coloring, interpolation="bilinear")
plt.axis("off")
plt.show()
# save wordcloud
wc.to_file(path.join(d, imgname2))
| mit | 58e241a2f8b07996a70fa855eed15847 | 30.350515 | 104 | 0.71095 | 3.028884 | false | false | false | false |
amueller/word_cloud | test/test_wordcloud.py | 1 | 15080 | from wordcloud import WordCloud, get_single_color_func, ImageColorGenerator
import numpy as np
import pytest
from random import Random
from numpy.testing import assert_array_equal
from PIL import Image
import xml.etree.ElementTree as ET
import matplotlib
matplotlib.use('Agg')
THIS = """The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
3 . 14 15 92 65 35 89 79 32 38 46 26 433
83 27 95 02 88 41 97 16 93 99 37 510
58 20 97 49 44 59 23 07 81 64 06 286
20 89 98 62 80 34 82 53 42 11 70 679
82 14 80 86 51 32 82 30 66 47 09 384
46 09 55 05 82 23 17 25 35 94 08 128
"""
STOPWORDED_COLLOCATIONS = """
thank you very much
thank you very much
thank you very much
thanks
"""
STOPWORDED_COLLOCATIONS_UPPERCASE = """
Thank you very much
Thank you very much
Thank you very much
thank you very much
hi There
Hi there
Hi There
thanks
"""
SMALL_CANVAS = """
better late than never someone will say
"""
def test_collocations():
wc = WordCloud(collocations=False, stopwords=set())
wc.generate(THIS)
wc2 = WordCloud(collocations=True, stopwords=set())
wc2.generate(THIS)
assert "is better" in wc2.words_
assert "is better" not in wc.words_
assert "way may" not in wc2.words_
def test_collocation_stopwords():
wc = WordCloud(collocations=True, stopwords={"you", "very"}, collocation_threshold=9)
wc.generate(STOPWORDED_COLLOCATIONS)
assert "thank you" not in wc.words_
assert "very much" not in wc.words_
assert "thank" in wc.words_
# a bigram of all stopwords will be removed
assert "you very" not in wc.words_
def test_collocation_stopwords_uppercase():
wc = WordCloud(collocations=True, stopwords={"thank", "hi", "there"}, collocation_threshold=9)
wc.generate(STOPWORDED_COLLOCATIONS_UPPERCASE)
assert "Thank you" not in wc.words_
assert "thank you" not in wc.words_
assert "Thank" not in wc.words_
# a bigram of all stopwords will be removed
assert "hi There" not in wc.words_
assert "Hi there" not in wc.words_
assert "Hi There" not in wc.words_
def test_plurals_numbers():
text = THIS + "\n" + "1 idea 2 ideas three ideas although many Ideas"
wc = WordCloud(stopwords=[]).generate(text)
# not capitalized usually
assert "Ideas" not in wc.words_
# plural removed
assert "ideas" not in wc.words_
# usually capitalized
assert "although" not in wc.words_
assert "idea" in wc.words_
assert "Although" in wc.words_
assert "better than" in wc.words_
def test_multiple_s():
text = 'flo flos floss flosss'
wc = WordCloud(stopwords=[]).generate(text)
assert "flo" in wc.words_
assert "flos" not in wc.words_
assert "floss" in wc.words_
assert "flosss" in wc.words_
# not normalizing means that the one with just one s is kept
wc = WordCloud(stopwords=[], normalize_plurals=False).generate(text)
assert "flo" in wc.words_
assert "flos" in wc.words_
assert "floss" in wc.words_
assert "flosss" in wc.words_
def test_empty_text():
# test originally empty text raises an exception
wc = WordCloud(stopwords=[])
with pytest.raises(ValueError):
wc.generate('')
# test empty-after-filtering text raises an exception
wc = WordCloud(stopwords=['a', 'b'])
with pytest.raises(ValueError):
wc.generate('a b a')
def test_default():
# test that default word cloud creation and conversions work
wc = WordCloud(max_words=50)
wc.generate(THIS)
# check for proper word extraction
assert len(wc.words_) == wc.max_words
# check that we got enough words
assert len(wc.layout_) == wc.max_words
# check image export
wc_image = wc.to_image()
assert wc_image.size == (wc.width, wc.height)
# check that numpy conversion works
wc_array = np.array(wc)
assert_array_equal(wc_array, wc.to_array())
# check size
assert wc_array.shape == (wc.height, wc.width, 3)
def test_stopwords_lowercasing():
# test that capitalized stopwords work.
wc = WordCloud(stopwords=["Beautiful"])
processed = wc.process_text(THIS)
words = [count[0] for count in processed]
assert "Beautiful" not in words
def test_writing_to_file(tmpdir):
wc = WordCloud()
wc.generate(THIS)
# check writing to file
filename = str(tmpdir.join("word_cloud.png"))
wc.to_file(filename)
loaded_image = Image.open(filename)
assert loaded_image.size == (wc.width, wc.height)
def test_check_errors():
wc = WordCloud()
try:
np.array(wc)
raise AssertionError("np.array(wc) didn't raise")
except ValueError as e:
assert "call generate" in str(e)
try:
wc.recolor()
raise AssertionError("wc.recolor didn't raise")
except ValueError as e:
assert "call generate" in str(e)
def test_svg_syntax():
wc = WordCloud()
wc.generate(THIS)
svg = wc.to_svg()
ET.fromstring(svg)
def test_recolor():
wc = WordCloud(max_words=50, colormap="jet")
wc.generate(THIS)
array_before = wc.to_array()
wc.recolor()
array_after = wc.to_array()
# check that the same places are filled
assert_array_equal(array_before.sum(axis=-1) != 0,
array_after.sum(axis=-1) != 0)
# check that they are not the same
assert np.abs(array_before - array_after).sum() > 10000
# check that recoloring is deterministic
wc.recolor(random_state=10)
wc_again = wc.to_array()
assert_array_equal(wc_again, wc.recolor(random_state=10))
def test_random_state():
# check that random state makes everything deterministic
wc = WordCloud(random_state=0)
wc2 = WordCloud(random_state=0)
wc.generate(THIS)
wc2.generate(THIS)
assert_array_equal(wc, wc2)
def test_mask():
# test masks
# check that using an empty mask is equivalent to not using a mask
wc = WordCloud(random_state=42)
wc.generate(THIS)
mask = np.zeros(np.array(wc).shape[:2], dtype=np.int)
wc_mask = WordCloud(mask=mask, random_state=42)
wc_mask.generate(THIS)
assert_array_equal(wc, wc_mask)
# use actual nonzero mask
mask = np.zeros((234, 456), dtype=np.int)
mask[100:150, 300:400] = 255
wc = WordCloud(mask=mask)
wc.generate(THIS)
wc_array = np.array(wc)
assert mask.shape == wc_array.shape[:2]
assert_array_equal(wc_array[mask != 0], 0)
assert wc_array[mask == 0].sum() > 10000
def test_mask_contour():
# test mask contour is created, learn more at:
# https://github.com/amueller/word_cloud/pull/348#issuecomment-370883873
mask = np.zeros((234, 456), dtype=np.int)
mask[100:150, 300:400] = 255
sm = WordCloud(mask=mask, contour_width=1, contour_color='blue')
sm.generate(THIS)
sm_array = np.array(sm)
sm_total = sm_array[100:150, 300:400].sum()
lg = WordCloud(mask=mask, contour_width=20, contour_color='blue')
lg.generate(THIS)
lg_array = np.array(lg)
lg_total = lg_array[100:150, 300:400].sum()
sc = WordCloud(mask=mask, contour_width=1, scale=2, contour_color='blue')
sc.generate(THIS)
sc_array = np.array(sc)
sc_total = sc_array[100:150, 300:400].sum()
# test `contour_width`
assert lg_total > sm_total
# test contour varies with `scale`
assert sc_total > sm_total
# test `contour_color`
assert all(sm_array[100, 300] == [0, 0, 255])
def test_single_color_func():
# test single color function for different color formats
random = Random(42)
red_function = get_single_color_func('red')
assert red_function(random_state=random) == 'rgb(181, 0, 0)'
hex_function = get_single_color_func('#00b4d2')
assert hex_function(random_state=random) == 'rgb(0, 48, 56)'
rgb_function = get_single_color_func('rgb(0,255,0)')
assert rgb_function(random_state=random) == 'rgb(0, 107, 0)'
rgb_perc_fun = get_single_color_func('rgb(80%,60%,40%)')
assert rgb_perc_fun(random_state=random) == 'rgb(97, 72, 48)'
hsl_function = get_single_color_func('hsl(0,100%,50%)')
assert hsl_function(random_state=random) == 'rgb(201, 0, 0)'
def test_single_color_func_grey():
# grey is special as it's a corner case
random = Random(42)
red_function = get_single_color_func('darkgrey')
assert red_function(random_state=random) == 'rgb(181, 181, 181)'
assert red_function(random_state=random) == 'rgb(56, 56, 56)'
def test_process_text():
# test that process function returns a dict
wc = WordCloud(max_words=50)
result = wc.process_text(THIS)
# check for proper return type
assert isinstance(result, dict)
def test_process_text_default_patterns():
wc = WordCloud(stopwords=set(), include_numbers=True, min_word_length=2)
words = wc.process_text(THIS)
wc2 = WordCloud(stopwords=set(), include_numbers=True, min_word_length=1)
words2 = wc2.process_text(THIS)
assert "a" not in words
assert "3" not in words
assert "a" in words2
assert "3" in words2
def test_process_text_regexp_parameter():
# test that word processing is influenced by `regexp`
wc = WordCloud(max_words=50, regexp=r'\w{5}')
words = wc.process_text(THIS)
assert 'than' not in words
def test_generate_from_frequencies():
# test that generate_from_frequencies() takes input argument dicts
wc = WordCloud(max_words=50)
words = wc.process_text(THIS)
result = wc.generate_from_frequencies(words)
assert isinstance(result, WordCloud)
def test_relative_scaling_zero():
# non-regression test for non-integer font size
wc = WordCloud(relative_scaling=0)
wc.generate(THIS)
def test_unicode_stopwords():
wc_unicode = WordCloud(stopwords=[u'Beautiful'])
try:
words_unicode = wc_unicode.process_text(unicode(THIS))
except NameError: # PY3
words_unicode = wc_unicode.process_text(THIS)
wc_str = WordCloud(stopwords=['Beautiful'])
words_str = wc_str.process_text(str(THIS))
assert words_unicode == words_str
def test_include_numbers():
wc_numbers = WordCloud(include_numbers=True)
wc = wc_numbers.process_text(THIS)
assert '14' in wc.keys()
def test_min_word_length():
wc_numbers = WordCloud(min_word_length=5)
wc = wc_numbers.process_text(THIS)
word_lengths = [len(word) for word in wc.keys()]
assert min(word_lengths) == 5
def test_recolor_too_small():
# check exception is raised when image is too small
colouring = np.array(Image.new('RGB', size=(20, 20)))
wc = WordCloud(width=30, height=30, random_state=0, min_font_size=1).generate(THIS)
image_colors = ImageColorGenerator(colouring)
with pytest.raises(ValueError, match='ImageColorGenerator is smaller than the canvas'):
wc.recolor(color_func=image_colors)
def test_recolor_too_small_set_default():
# check no exception is raised when default colour is used
colouring = np.array(Image.new('RGB', size=(20, 20)))
wc = WordCloud(max_words=50, width=30, height=30, min_font_size=1).generate(THIS)
image_colors = ImageColorGenerator(colouring, default_color=(0, 0, 0))
wc.recolor(color_func=image_colors)
def test_small_canvas():
# check font size fallback works on small canvas
wc = WordCloud(max_words=50, width=21, height=21)
wc.generate(SMALL_CANVAS)
assert len(wc.layout_) > 0
def test_tiny_canvas():
# check exception if canvas too small for fallback
w = WordCloud(max_words=50, width=1, height=1)
with pytest.raises(ValueError, match="Couldn't find space to draw"):
w.generate(THIS)
assert len(w.layout_) == 0
def test_coloring_black_works():
# check that using black colors works.
mask = np.zeros((50, 50, 3))
image_colors = ImageColorGenerator(mask)
wc = WordCloud(width=50, height=50, random_state=42,
color_func=image_colors, min_font_size=1)
wc.generate(THIS)
def test_repeat():
short_text = "Some short text"
wc = WordCloud(stopwords=[]).generate(short_text)
assert len(wc.layout_) == 3
wc = WordCloud(max_words=50, stopwords=[], repeat=True).generate(short_text)
# multiple of word count larger than max_words
assert len(wc.layout_) == 51
# relative scaling doesn't work well with repeat
assert wc.relative_scaling == 0
# all frequencies are 1
assert len(wc.words_) == 3
assert_array_equal(list(wc.words_.values()), 1)
frequencies = [w[0][1] for w in wc.layout_]
assert_array_equal(frequencies, 1)
repetition_text = "Some short text with text"
wc = WordCloud(max_words=52, stopwords=[], repeat=True)
wc.generate(repetition_text)
assert len(wc.words_) == 4
# normalized frequencies
assert wc.words_['text'] == 1
assert wc.words_['with'] == .5
assert len(wc.layout_), wc.max_words
frequencies = [w[0][1] for w in wc.layout_]
# check that frequencies are sorted
assert np.all(np.diff(frequencies) <= 0)
def test_zero_frequencies():
word_cloud = WordCloud()
word_cloud.generate_from_frequencies({'test': 1, 'test1': 0, 'test2': 0})
assert len(word_cloud.layout_) == 1
assert word_cloud.layout_[0][0][0] == 'test'
def test_plural_stopwords():
x = '''was was was was was was was was was was was was was was was
wa
hello hello hello hello hello hello hello hello
goodbye good bye maybe yes no'''
w = WordCloud().generate(x)
assert w.words_['wa'] < 1
w = WordCloud(collocations=False).generate(x)
assert w.words_['wa'] < 1
def test_max_font_size_as_mask_height():
# test if max font size will respect the mask height
x = '''hello hello hello
bye'''
# Get default wordcloud size
wcd = WordCloud()
default_size = (wcd.height, wcd.width)
# Make sure the size we are using is larger than the default size
size = (default_size[0] * 2, default_size[1] * 2)
# using mask, all drawable
mask = np.zeros(size, dtype=np.int)
mask[:, :] = 0
wc = WordCloud(mask=mask, random_state=42)
wc.generate(x)
# no mask
wc2 = WordCloud(width=size[1], height=size[0], random_state=42)
wc2.generate(x)
# Check if the biggest element has the same font size
assert wc.layout_[0][1] == wc2.layout_[0][1]
| mit | 9f4fa533473227a1ea4c52acc7c916e9 | 28.920635 | 98 | 0.667639 | 3.307743 | false | true | false | false |
materialsproject/custodian | custodian/utils.py | 1 | 1357 | """
Utility function and classes.
"""
import logging
import os
import tarfile
from glob import glob
def backup(filenames, prefix="error"):
"""
Backup files to a tar.gz file. Used, for example, in backing up the
files of an errored run before performing corrections.
Args:
filenames ([str]): List of files to backup. Supports wildcards, e.g.,
*.*.
prefix (str): prefix to the files. Defaults to error, which means a
series of error.1.tar.gz, error.2.tar.gz, ... will be generated.
"""
num = max([0] + [int(f.split(".")[1]) for f in glob(f"{prefix}.*.tar.gz")])
filename = f"{prefix}.{num + 1}.tar.gz"
logging.info(f"Backing up run to {filename}.")
with tarfile.open(filename, "w:gz") as tar:
for fname in filenames:
for f in glob(fname):
tar.add(f)
def get_execution_host_info():
"""
Tries to return a tuple describing the execution host.
Doesn't work for all queueing systems
Returns:
(HOSTNAME, CLUSTER_NAME)
"""
host = os.environ.get("HOSTNAME", None)
cluster = os.environ.get("SGE_O_HOST", None)
if host is None:
try:
import socket
host = host or socket.gethostname()
except Exception:
pass
return host or "unknown", cluster or "unknown"
| mit | 9d4ad357f557ac2b08eb7e71c86e78cb | 27.270833 | 79 | 0.599853 | 3.790503 | false | false | false | false |
materialsproject/custodian | custodian/tests/test_custodian.py | 1 | 9650 | import glob
import os
import random
import subprocess
import unittest
from ruamel import yaml
from custodian.custodian import (
Custodian,
ErrorHandler,
Job,
MaxCorrectionsError,
MaxCorrectionsPerHandlerError,
MaxCorrectionsPerJobError,
NonRecoverableError,
ReturnCodeError,
ValidationError,
Validator,
)
class ExitCodeJob(Job):
def __init__(self, exitcode=0):
self.exitcode = exitcode
def setup(self):
pass
def run(self):
return subprocess.Popen(f"exit {self.exitcode}", shell=True)
def postprocess(self):
pass
class ExampleJob(Job):
def __init__(self, jobid, params=None):
if params is None:
params = {"initial": 0, "total": 0}
self.jobid = jobid
self.params = params
def setup(self):
self.params["initial"] = 0
self.params["total"] = 0
def run(self):
sequence = [random.uniform(0, 1) for i in range(100)]
self.params["total"] = self.params["initial"] + sum(sequence)
def postprocess(self):
pass
@property
def name(self):
return f"ExampleJob{self.jobid}"
class ExampleHandler(ErrorHandler):
def __init__(self, params):
self.params = params
def check(self):
return self.params["total"] < 50
def correct(self):
self.params["initial"] += 1
return {"errors": "total < 50", "actions": "increment by 1"}
class ExampleHandler1b(ExampleHandler):
"""
This handler always can apply a correction, but will only apply it twice before raising.
"""
max_num_corrections = 2 # type: ignore
raise_on_max = True
class ExampleHandler1c(ExampleHandler):
"""
This handler always can apply a correction, but will only apply it twice and then not anymore.
"""
max_num_corrections = 2 # type: ignore
raise_on_max = False
class ExampleHandler2(ErrorHandler):
"""
This handler always result in an error.
"""
def __init__(self, params):
self.params = params
self.has_error = False
def check(self):
return True
def correct(self):
self.has_error = True
return {"errors": "Unrecoverable error", "actions": None}
class ExampleHandler2b(ExampleHandler2):
"""
This handler always result in an error. No runtime error though
"""
raises_runtime_error = False
def correct(self):
self.has_error = True
return {"errors": "Unrecoverable error", "actions": []}
class ExampleValidator1(Validator):
def __init__(self):
pass
def check(self):
return False
class ExampleValidator2(Validator):
def __init__(self):
pass
def check(self):
return True
class CustodianTest(unittest.TestCase):
def setUp(self):
self.cwd = os.getcwd()
os.chdir(os.path.abspath(os.path.dirname(__file__)))
def test_exitcode_error(self):
c = Custodian([], [ExitCodeJob(0)])
c.run()
c = Custodian([], [ExitCodeJob(1)])
self.assertRaises(ReturnCodeError, c.run)
self.assertTrue(c.run_log[-1]["nonzero_return_code"])
c = Custodian([], [ExitCodeJob(1)], terminate_on_nonzero_returncode=False)
c.run()
def test_run(self):
njobs = 100
params = {"initial": 0, "total": 0}
c = Custodian(
[ExampleHandler(params)],
[ExampleJob(i, params) for i in range(njobs)],
max_errors=njobs,
)
output = c.run()
self.assertEqual(len(output), njobs)
ExampleHandler(params).as_dict()
def test_run_interrupted(self):
njobs = 100
params = {"initial": 0, "total": 0}
c = Custodian(
[ExampleHandler(params)],
[ExampleJob(i, params) for i in range(njobs)],
max_errors=njobs,
)
self.assertEqual(c.run_interrupted(), njobs)
self.assertEqual(c.run_interrupted(), njobs)
total_done = 1
while total_done < njobs:
c.jobs[njobs - 1].run()
if params["total"] > 50:
self.assertEqual(c.run_interrupted(), njobs - total_done)
total_done += 1
def test_unrecoverable(self):
njobs = 100
params = {"initial": 0, "total": 0}
h = ExampleHandler2(params)
c = Custodian([h], [ExampleJob(i, params) for i in range(njobs)], max_errors=njobs)
self.assertRaises(NonRecoverableError, c.run)
self.assertTrue(h.has_error)
h = ExampleHandler2b(params)
c = Custodian([h], [ExampleJob(i, params) for i in range(njobs)], max_errors=njobs)
c.run()
self.assertTrue(h.has_error)
self.assertEqual(c.run_log[-1]["handler"], h)
def test_max_errors(self):
njobs = 100
params = {"initial": 0, "total": 0}
h = ExampleHandler(params)
c = Custodian(
[h],
[ExampleJob(i, params) for i in range(njobs)],
max_errors=1,
max_errors_per_job=10,
)
self.assertRaises(MaxCorrectionsError, c.run)
self.assertTrue(c.run_log[-1]["max_errors"])
def test_max_errors_per_job(self):
njobs = 100
params = {"initial": 0, "total": 0}
h = ExampleHandler(params)
c = Custodian(
[h],
[ExampleJob(i, params) for i in range(njobs)],
max_errors=njobs,
max_errors_per_job=1,
)
self.assertRaises(MaxCorrectionsPerJobError, c.run)
self.assertTrue(c.run_log[-1]["max_errors_per_job"])
def test_max_errors_per_handler_raise(self):
njobs = 100
params = {"initial": 0, "total": 0}
h = ExampleHandler1b(params)
c = Custodian(
[h],
[ExampleJob(i, params) for i in range(njobs)],
max_errors=njobs * 10,
max_errors_per_job=1000,
)
self.assertRaises(MaxCorrectionsPerHandlerError, c.run)
self.assertEqual(h.n_applied_corrections, 2)
self.assertEqual(len(c.run_log[-1]["corrections"]), 2)
self.assertTrue(c.run_log[-1]["max_errors_per_handler"])
self.assertEqual(c.run_log[-1]["handler"], h)
def test_max_errors_per_handler_warning(self):
njobs = 100
params = {"initial": 0, "total": 0}
c = Custodian(
[ExampleHandler1c(params)],
[ExampleJob(i, params) for i in range(njobs)],
max_errors=njobs * 10,
max_errors_per_job=1000,
)
c.run()
self.assertTrue(all(len(r["corrections"]) <= 2 for r in c.run_log))
def test_validators(self):
njobs = 100
params = {"initial": 0, "total": 0}
c = Custodian(
[ExampleHandler(params)],
[ExampleJob(i, params) for i in range(njobs)],
[ExampleValidator1()],
max_errors=njobs,
)
output = c.run()
self.assertEqual(len(output), njobs)
njobs = 100
params = {"initial": 0, "total": 0}
v = ExampleValidator2()
c = Custodian(
[ExampleHandler(params)],
[ExampleJob(i, params) for i in range(njobs)],
[v],
max_errors=njobs,
)
self.assertRaises(ValidationError, c.run)
self.assertEqual(c.run_log[-1]["validator"], v)
def test_from_spec(self):
spec = """jobs:
- jb: custodian.vasp.jobs.VaspJob
params:
final: False
suffix: .relax1
- jb: custodian.vasp.jobs.VaspJob
params:
final: True
suffix: .relax2
settings_override: {"file": "CONTCAR", "action": {"_file_copy": {"dest": "POSCAR"}}}
jobs_common_params:
$vasp_cmd: ["mpirun", "-machinefile", "$PBS_NODEFILE", "-np", "24", "/opt/vasp/5.4.1/bin/vasp"]
handlers:
- hdlr: custodian.vasp.handlers.VaspErrorHandler
- hdlr: custodian.vasp.handlers.AliasingErrorHandler
- hdlr: custodian.vasp.handlers.MeshSymmetryErrorHandler
validators:
- vldr: custodian.vasp.validators.VasprunXMLValidator
custodian_params:
$scratch_dir: $TMPDIR"""
os.environ["TMPDIR"] = "/tmp/random"
os.environ["PBS_NODEFILE"] = "whatever"
d = yaml.safe_load(spec)
c = Custodian.from_spec(d)
self.assertEqual(c.jobs[0].vasp_cmd[2], "whatever")
self.assertEqual(c.scratch_dir, "/tmp/random")
self.assertEqual(len(c.jobs), 2)
self.assertEqual(len(c.handlers), 3)
self.assertEqual(len(c.validators), 1)
def tearDown(self):
for f in glob.glob("custodian.*.tar.gz"):
os.remove(f)
try:
os.remove("custodian.json")
except OSError:
pass # Ignore if file cannot be found.
os.chdir(self.cwd)
# class CustodianCheckpointTest(unittest.TestCase):
# def test_checkpoint_loading(self):
# self.cwd = os.getcwd()
# pth = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "test_files", "checkpointing")
# # os.chdir()
# shutil.copy(os.path.join(pth, "backup.tar.gz"), "custodian.chk.3.tar.gz")
# njobs = 5
# params = {"initial": 0, "total": 0}
# c = Custodian(
# [ExampleHandler(params)],
# [ExampleJob(i, params) for i in range(njobs)],
# [ExampleValidator1()],
# max_errors=100,
# checkpoint=True,
# )
# self.assertEqual(len(c.run_log), 3)
# self.assertEqual(len(c.run()), 5)
# os.remove("custodian.json")
# os.chdir(self.cwd)
if __name__ == "__main__":
unittest.main()
| mit | 7f626e9495929a5e2a948f71a94ff372 | 27.80597 | 115 | 0.575544 | 3.482497 | false | true | false | false |
amueller/word_cloud | examples/colored_by_group.py | 2 | 4405 | #!/usr/bin/env python
"""
Colored by Group Example
========================
Generating a word cloud that assigns colors to words based on
a predefined mapping from colors to words
"""
from wordcloud import (WordCloud, get_single_color_func)
import matplotlib.pyplot as plt
class SimpleGroupedColorFunc(object):
"""Create a color function object which assigns EXACT colors
to certain words based on the color to words mapping
Parameters
----------
color_to_words : dict(str -> list(str))
A dictionary that maps a color to the list of words.
default_color : str
Color that will be assigned to a word that's not a member
of any value from color_to_words.
"""
def __init__(self, color_to_words, default_color):
self.word_to_color = {word: color
for (color, words) in color_to_words.items()
for word in words}
self.default_color = default_color
def __call__(self, word, **kwargs):
return self.word_to_color.get(word, self.default_color)
class GroupedColorFunc(object):
"""Create a color function object which assigns DIFFERENT SHADES of
specified colors to certain words based on the color to words mapping.
Uses wordcloud.get_single_color_func
Parameters
----------
color_to_words : dict(str -> list(str))
A dictionary that maps a color to the list of words.
default_color : str
Color that will be assigned to a word that's not a member
of any value from color_to_words.
"""
def __init__(self, color_to_words, default_color):
self.color_func_to_words = [
(get_single_color_func(color), set(words))
for (color, words) in color_to_words.items()]
self.default_color_func = get_single_color_func(default_color)
def get_color_func(self, word):
"""Returns a single_color_func associated with the word"""
try:
color_func = next(
color_func for (color_func, words) in self.color_func_to_words
if word in words)
except StopIteration:
color_func = self.default_color_func
return color_func
def __call__(self, word, **kwargs):
return self.get_color_func(word)(word, **kwargs)
text = """The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"""
# Since the text is small collocations are turned off and text is lower-cased
wc = WordCloud(collocations=False).generate(text.lower())
color_to_words = {
# words below will be colored with a green single color function
'#00ff00': ['beautiful', 'explicit', 'simple', 'sparse',
'readability', 'rules', 'practicality',
'explicitly', 'one', 'now', 'easy', 'obvious', 'better'],
# will be colored with a red single color function
'red': ['ugly', 'implicit', 'complex', 'complicated', 'nested',
'dense', 'special', 'errors', 'silently', 'ambiguity',
'guess', 'hard']
}
# Words that are not in any of the color_to_words values
# will be colored with a grey single color function
default_color = 'grey'
# Create a color function with single tone
# grouped_color_func = SimpleGroupedColorFunc(color_to_words, default_color)
# Create a color function with multiple tones
grouped_color_func = GroupedColorFunc(color_to_words, default_color)
# Apply our color function
wc.recolor(color_func=grouped_color_func)
# Plot
plt.figure()
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()
| mit | af6d1ec8fc73794a82b83dea41623557 | 33.147287 | 78 | 0.663791 | 3.88448 | false | false | false | false |
materialsproject/custodian | custodian/cp2k/jobs.py | 1 | 13203 | """
This module implements basic kinds of jobs for Cp2k runs.
"""
import logging
import os
import shutil
import subprocess
from monty.os.path import zpath
from monty.shutil import decompress_dir
from pymatgen.io.cp2k.inputs import Cp2kInput, Keyword
from custodian.cp2k.interpreter import Cp2kModder
from custodian.cp2k.utils import cleanup_input, restart
from custodian.custodian import Job
logger = logging.getLogger(__name__)
__author__ = "Nicholas Winner"
__version__ = "1.0"
CP2K_INPUT_FILES = ["cp2k.inp"]
CP2K_OUTPUT_FILES = ["cp2k.out"]
class Cp2kJob(Job):
"""
A basic cp2k job. Just runs whatever is in the directory. But conceivably
can be a complex processing of inputs etc. with initialization.
"""
def __init__(
self,
cp2k_cmd,
input_file="cp2k.inp",
output_file="cp2k.out",
stderr_file="std_err.txt",
suffix="",
final=True,
backup=True,
settings_override=None,
restart=False,
):
"""
This constructor is necessarily complex due to the need for
flexibility. For standard kinds of runs, it's often better to use one
of the static constructors. The defaults are usually fine too.
Args:
cp2k_cmd (list): Command to run cp2k as a list of args. For example,
if you are using mpirun, it can be something like
["mpirun", "cp2k.popt"]
input_file (str): Name of the file to use as input to CP2K
executable. Defaults to "cp2k.inp"
output_file (str): Name of file to direct standard out to.
Defaults to "cp2k.out".
stderr_file (str): Name of file to direct standard error to.
Defaults to "std_err.txt".
suffix (str): A suffix to be appended to the final output. E.g.,
to rename all CP2K output from say cp2k.out to
cp2k.out.relax1, provide ".relax1" as the suffix.
final (bool): Indicating whether this is the final cp2k job in a
series. Defaults to True.
backup (bool): Whether to backup the initial input files. If True,
the input file will be copied with a
".orig" appended. Defaults to True.
settings_override ([actions]): A list of actions. See the Cp2kModder
in interpreter.py
restart (bool): Whether to run in restart mode, i.e. this a continuation of
a previous calculation. Default is False.
"""
self.cp2k_cmd = cp2k_cmd
self.input_file = input_file
self.ci = None
self.output_file = output_file
self.stderr_file = stderr_file
self.final = final
self.backup = backup
self.suffix = suffix
self.settings_override = settings_override if settings_override else []
self.restart = restart
def setup(self):
"""
Performs initial setup for Cp2k in three stages. First, if custodian is running in restart mode, then
the restart function will copy the restart file to self.input_file, and remove any previous WFN initialization
if present. Second, any additional user specified settings will be applied. Lastly, a backup of the input
file will be made for reference.
"""
decompress_dir(".")
self.ci = Cp2kInput.from_file(zpath(self.input_file))
cleanup_input(self.ci)
if self.restart:
restart(
actions=self.settings_override,
output_file=self.output_file,
input_file=self.input_file,
no_actions_needed=True,
)
if self.settings_override or self.restart:
modder = Cp2kModder(filename=self.input_file, actions=[], ci=self.ci)
modder.apply_actions(self.settings_override)
if self.backup:
shutil.copy(self.input_file, f"{self.input_file}.orig")
def run(self):
"""
Perform the actual CP2K run.
Returns:
(subprocess.Popen) Used for monitoring.
"""
# TODO: cp2k has bizarre in/out streams. Some errors that should go to std_err are not sent anywhere...
cmd = list(self.cp2k_cmd)
cmd.extend(["-i", self.input_file])
cmdstring = " ".join(cmd)
logger.info(f"Running {cmdstring}")
with open(self.output_file, "w") as f_std, open(self.stderr_file, "w", buffering=1) as f_err:
# use line buffering for stderr
return subprocess.Popen(cmd, stdout=f_std, stderr=f_err, shell=False)
# TODO double jobs, file manipulations, etc. should be done in atomate in the future
# and custodian should only run the job itself
def postprocess(self):
"""
Postprocessing includes renaming and gzipping where necessary.
"""
fs = os.listdir(".")
if os.path.exists(self.output_file):
if self.suffix != "":
os.mkdir(f"run{self.suffix}")
for f in fs:
if "json" in f:
continue
if not os.path.isdir(f):
if self.final:
shutil.move(f, f"run{self.suffix}/{f}")
else:
shutil.copy(f, f"run{self.suffix}/{f}")
# Remove continuation so if a subsequent job is run in
# the same directory, will not restart this job.
if os.path.exists("continue.json"):
os.remove("continue.json")
def terminate(self):
"""
Terminate cp2k
"""
for k in self.cp2k_cmd:
if "cp2k" in k:
try:
os.system(f"killall {k}")
except Exception:
pass
@classmethod
def gga_static_to_hybrid(
cls,
cp2k_cmd,
input_file="cp2k.inp",
output_file="cp2k.out",
stderr_file="std_err.txt",
backup=True,
settings_override_gga=None,
settings_override_hybrid=None,
):
"""
A bare gga to hybrid calculation. Removes all unecessary features
from the gga run, and making it only a ENERGY/ENERGY_FORCE
depending on the hybrid run.
"""
job1_settings_override = [
{
"dict": input_file,
"action": {
"_unset": {"FORCE_EVAL": {"DFT": "XC"}},
"_set": {"GLOBAL": {"PROJECT_NAME": "GGA", "RUN_TYPE": "ENERGY_FORCE"}},
},
},
{
"dict": input_file,
"action": {"_set": {"FORCE_EVAL": {"DFT": {"XC": {"XC_FUNCTIONAL": {"PBE": {}}}}}}},
},
]
job1 = Cp2kJob(
cp2k_cmd,
input_file=input_file,
output_file=output_file,
backup=backup,
stderr_file=stderr_file,
final=False,
suffix="1",
settings_override=job1_settings_override,
)
ci = Cp2kInput.from_file(zpath(input_file))
r = ci["global"].get("run_type", Keyword("RUN_TYPE", "ENERGY_FORCE")).values[0]
if r in ["ENERGY", "WAVEFUNCTION_OPTIMIZATION", "WFN_OPT", "ENERGY_FORCE"]: # no need for double job
return [job1]
job2_settings_override = [
{
"dict": input_file,
"action": {
"_set": {
"FORCE_EVAL": {
"DFT": {
"XC": {
"HF": {
"SCREENING": {
"SCREEN_ON_INITIAL_P": True,
"SCREEN_P_FORCES": True,
}
}
},
"WFN_RESTART_FILE_NAME": "GGA-RESTART.wfn",
}
},
"GLOBAL": {"RUN_TYPE": r},
},
},
}
]
job2 = Cp2kJob(
cp2k_cmd,
input_file=input_file,
output_file=output_file,
backup=backup,
stderr_file=stderr_file,
final=True,
suffix="2",
restart=False,
settings_override=job2_settings_override,
)
return [job1, job2]
@classmethod
def double_job(
cls, cp2k_cmd, input_file="cp2k.inp", output_file="cp2k.out", stderr_file="std_err.txt", backup=True
):
"""
This creates a sequence of two jobs. The first of which is an "initialization" of the
wfn. Using this, the "restart" function can be exploited to determine if a diagonalization
job can/would benefit from switching to OT scheme. If not, then the second job remains a
diagonalization job, and there is minimal overhead from restarting.
"""
job1 = Cp2kJob(
cp2k_cmd,
input_file=input_file,
output_file=output_file,
backup=backup,
stderr_file=stderr_file,
final=False,
suffix="1",
settings_override={},
)
ci = Cp2kInput.from_file(zpath(input_file))
r = ci["global"].get("run_type", Keyword("RUN_TYPE", "ENERGY_FORCE")).values[0]
if r not in ["ENERGY", "WAVEFUNCTION_OPTIMIZATION", "WFN_OPT"]:
job1.settings_override = [
{"dict": input_file, "action": {"_set": {"GLOBAL": {"RUN_TYPE": "ENERGY_FORCE"}}}}
]
job2 = Cp2kJob(
cp2k_cmd,
input_file=input_file,
output_file=output_file,
backup=backup,
stderr_file=stderr_file,
final=True,
suffix="2",
restart=True,
)
job2.settings_override = [{"dict": input_file, "action": {"_set": {"GLOBAL": {"RUN_TYPE": r}}}}]
return [job1, job2]
@classmethod
def pre_screen_hybrid(
cls, cp2k_cmd, input_file="cp2k.inp", output_file="cp2k.out", stderr_file="std_err.txt", backup=True
):
"""
Build a job where the first job is an unscreened hybrid static calculation, then the second one
uses the wfn from the first job as a restart to do a screened calculation.
"""
job1_settings_override = [
{
"dict": input_file,
"action": {
"_set": {
"FORCE_EVAL": {
"DFT": {
"XC": {
"HF": {
"SCREENING": {
"SCREEN_ON_INITIAL_P": False,
"SCREEN_P_FORCES": False,
}
}
}
}
},
"GLOBAL": {"RUN_TYPE": "ENERGY_FORCE"},
}
},
}
]
job1 = Cp2kJob(
cp2k_cmd,
input_file=input_file,
output_file=output_file,
backup=backup,
stderr_file=stderr_file,
final=False,
suffix="1",
settings_override=job1_settings_override,
)
ci = Cp2kInput.from_file(zpath(input_file))
r = ci["global"].get("run_type", Keyword("RUN_TYPE", "ENERGY_FORCE")).values[0]
if r in ["ENERGY", "WAVEFUNCTION_OPTIMIZATION", "WFN_OPT", "ENERGY_FORCE"]: # no need for double job
return [job1]
job2_settings_override = [
{
"dict": input_file,
"action": {
"_set": {
"FORCE_EVAL": {
"DFT": {
"XC": {
"HF": {
"SCREENING": {
"SCREEN_ON_INITIAL_P": True,
"SCREEN_P_FORCES": True,
}
}
},
"WFN_RESTART_FILE_NAME": "UNSCREENED_HYBRID-RESTART.wfn",
}
},
"GLOBAL": {"RUN_TYPE": r},
},
},
}
]
job2 = Cp2kJob(
cp2k_cmd,
input_file=input_file,
output_file=output_file,
backup=backup,
stderr_file=stderr_file,
final=True,
suffix="2",
restart=False,
settings_override=job2_settings_override,
)
return [job1, job2]
| mit | a61ba09d560fa712b553d2adb2d2eb1a | 34.302139 | 118 | 0.479512 | 4.219559 | false | false | false | false |
materialsproject/custodian | custodian/vasp/interpreter.py | 1 | 2115 | """
Implements various interpreters and modders for VASP.
"""
from pymatgen.io.vasp.inputs import VaspInput
from custodian.ansible.actions import DictActions, FileActions
from custodian.ansible.interpreter import Modder
class VaspModder(Modder):
"""
A Modder for VaspInputSets.
"""
def __init__(self, actions=None, strict=True, vi=None):
"""
Initializes a Modder for VaspInput sets
Args:
actions ([Action]): A sequence of supported actions. See
:mod:`custodian.ansible.actions`. Default is None,
which means DictActions and FileActions are supported.
strict (bool): Indicating whether to use strict mode. In non-strict
mode, unsupported actions are simply ignored without any
errors raised. In strict mode, if an unsupported action is
supplied, a ValueError is raised. Defaults to True.
vi (VaspInput): A VaspInput object from the current directory.
Initialized automatically if not passed (but passing it will
avoid having to reparse the directory).
"""
self.vi = vi or VaspInput.from_directory(".")
actions = actions or [FileActions, DictActions]
super().__init__(actions, strict)
def apply_actions(self, actions):
"""
Applies a list of actions to the Vasp Input Set and rewrites modified
files.
Args:
actions [dict]: A list of actions of the form {'file': filename,
'action': moddermodification} or {'dict': vaspinput_key,
'action': moddermodification}
"""
modified = []
for a in actions:
if "dict" in a:
k = a["dict"]
modified.append(k)
self.vi[k] = self.modify_object(a["action"], self.vi[k])
elif "file" in a:
self.modify(a["action"], a["file"])
else:
raise ValueError(f"Unrecognized format: {a}")
for f in modified:
self.vi[f].write_file(f)
| mit | 52d69943a17917c1fbace1790b1260d8 | 36.767857 | 79 | 0.586761 | 4.387967 | false | false | false | false |
materialsproject/custodian | custodian/cp2k/interpreter.py | 1 | 3508 | """
CP2K adapted interpreter and modder for custodian.
"""
from pymatgen.io.cp2k.inputs import Cp2kInput
from custodian.ansible.actions import DictActions, FileActions
from custodian.ansible.interpreter import Modder
from custodian.cp2k.utils import cleanup_input
__author__ = "Nicholas Winner"
__version__ = "1.0"
__email__ = "nwinner@berkeley.edu"
__date__ = "October 2021"
class Cp2kModder(Modder):
"""
Cp2kModder is a lightweight class for applying modifications to cp2k input files. It
also supports modifications that are file operations (e.g. copying).
"""
def __init__(self, filename="cp2k.inp", actions=None, strict=True, ci=None):
"""
Initializes a Modder for Cp2kInput sets
Args:
filename (str): name of cp2k input file to modify. This file will be overwritten
if actions are applied.
actions ([Action]): A sequence of supported actions. See
:mod:`custodian.ansible.actions`. Default is None,
which means DictActions and FileActions are supported.
strict (bool): Indicating whether to use strict mode. In non-strict
mode, unsupported actions are simply ignored without any
errors raised. In strict mode, if an unsupported action is
supplied, a ValueError is raised. Defaults to True.
ci (Cp2kInput): A Cp2kInput object from the current directory.
Initialized automatically if not passed (but passing it will
avoid having to reparse the directory).
"""
self.ci = ci or Cp2kInput.from_file(filename)
self.filename = filename
actions = actions or [FileActions, DictActions]
super().__init__(actions, strict)
def apply_actions(self, actions):
"""
Applies a list of actions to the CP2K Input Set and rewrites modified
files.
Args:
actions [dict]: A list of actions of the form {'file': filename,
'action': moddermodification} or {'dict': cp2k_key,
'action': moddermodification}
"""
modified = []
for a in actions:
if "dict" in a:
k = a["dict"]
modified.append(k)
Cp2kModder._modify(a["action"], self.ci)
elif "file" in a:
self.modify(a["action"], a["file"])
self.ci = Cp2kInput.from_file(self.filename)
else:
raise ValueError(f"Unrecognized format: {a}")
cleanup_input(self.ci)
self.ci.write_file(self.filename)
@staticmethod
def _modify(modification, obj):
"""
Note that modify makes actual in-place modifications. It does not
return a copy.
Args:
modification (dict): Modification must be {action_keyword :
settings}. E.g., {'_set': {'Hello':'Universe', 'Bye': 'World'}}
obj (dict/str/object): Object to modify depending on actions. For
example, for DictActions, obj will be a dict to be modified.
For FileActions, obj will be a string with a full pathname to a
file.
"""
modification = list(modification.items()) if isinstance(modification, dict) else modification
for action, settings in modification:
try:
getattr(obj, action[1:])(settings)
except KeyError:
continue
| mit | d3f21a2149c20678642f8268f6170962 | 38.863636 | 101 | 0.598632 | 4.252121 | false | false | false | false |
materialsproject/custodian | custodian/vasp/validators.py | 1 | 4852 | """
Implements various validatiors, e.g., check if vasprun.xml is valid, for VASP.
"""
import logging
import os
from collections import deque
from pymatgen.io.vasp import Chgcar, Incar, Outcar, Vasprun
from custodian.custodian import Validator
class VasprunXMLValidator(Validator):
"""
Checks that a valid vasprun.xml was generated
"""
def __init__(self, output_file="vasp.out", stderr_file="std_err.txt"):
"""
Args:
output_file (str): Name of file VASP standard output is directed to.
Defaults to "vasp.out".
stderr_file (str): Name of file VASP standard error is direct to.
Defaults to "std_err.txt".
"""
self.output_file = output_file
self.stderr_file = stderr_file
self.logger = logging.getLogger(self.__class__.__name__)
def check(self):
"""
Check for error.
"""
try:
Vasprun("vasprun.xml")
except Exception:
exception_context = {}
if os.path.exists(self.output_file):
with open(self.output_file) as output_file:
output_file_tail = deque(output_file, maxlen=10)
exception_context["output_file_tail"] = "".join(output_file_tail)
if os.path.exists(self.stderr_file):
with open(self.stderr_file) as stderr_file:
stderr_file_tail = deque(stderr_file, maxlen=10)
exception_context["stderr_file_tail"] = "".join(stderr_file_tail)
if os.path.exists("vasprun.xml"):
stat = os.stat("vasprun.xml")
exception_context["vasprun_st_size"] = stat.st_size
exception_context["vasprun_st_atime"] = stat.st_atime
exception_context["vasprun_st_mtime"] = stat.st_mtime
exception_context["vasprun_st_ctime"] = stat.st_ctime
with open("vasprun.xml") as vasprun:
vasprun_tail = deque(vasprun, maxlen=10)
exception_context["vasprun_tail"] = "".join(vasprun_tail)
self.logger.error("Failed to load vasprun.xml", exc_info=True, extra=exception_context)
return True
return False
class VaspFilesValidator(Validator):
"""
Check for existence of some of the files that VASP
normally create upon running.
"""
def __init__(self):
"""
Dummy init
"""
def check(self):
"""
Check for error.
"""
for vfile in ["CONTCAR", "OSZICAR", "OUTCAR"]:
if not os.path.exists(vfile):
return True
return False
class VaspNpTMDValidator(Validator):
"""
Check NpT-AIMD settings is loaded by VASP compiled with -Dtbdyn.
Currently, VASP only have Langevin thermostat (MDALGO = 3) for NpT ensemble.
"""
def __init__(self):
"""
Dummy init.
"""
def check(self):
"""
Check for error.
"""
incar = Incar.from_file("INCAR")
is_npt = incar.get("MDALGO") == 3
if not is_npt:
return False
outcar = Outcar("OUTCAR")
patterns = {"MDALGO": r"MDALGO\s+=\s+([\d]+)"}
outcar.read_pattern(patterns=patterns)
if outcar.data["MDALGO"] == [["3"]]:
return False
return True
class VaspAECCARValidator(Validator):
"""
Check if the data in the AECCAR is corrupted
"""
def __init__(self):
"""
Dummy init
"""
def check(self):
"""
Check for error.
"""
aeccar0 = Chgcar.from_file("AECCAR0")
aeccar2 = Chgcar.from_file("AECCAR2")
aeccar = aeccar0 + aeccar2
return check_broken_chgcar(aeccar)
def check_broken_chgcar(chgcar, diff_thresh=None):
"""
Check if the charge density file is corrupt
Args:
chgcar (Chgcar): Chgcar-like object.
diff_thresh (Float): Threshold for diagonal difference.
None means we won't check for this.
"""
chgcar_data = chgcar.data["total"]
if (chgcar_data < 0).sum() > 100:
# a decent bunch of the values are negative this for sure means a broken charge density
return True
if diff_thresh:
"""
If any one diagonal difference accounts for more than a particular portion of
the total difference between highest and lowest density.
When we are looking at AECCAR data, since the charge density is so high near the core
and we have a course grid, this threshold can be as high as 0.99
"""
diff = chgcar_data[:-1, :-1, :-1] - chgcar_data[1:, 1:, 1:]
if diff.max() / (chgcar_data.max() - chgcar_data.min()) > diff_thresh:
return True
return False
| mit | bf74b8a19e41340cff7de00e467ea16b | 29.325 | 99 | 0.567189 | 3.790625 | false | false | false | false |
amueller/word_cloud | wordcloud/_version.py | 1 | 18455 |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains the computed version number.
# This file is released into the public domain. Generated by
# versioneer-0.18 (https://github.com/warner/python-versioneer)
"""Git implementation of _version.py."""
import errno
import os
import re
import subprocess
import sys
def get_keywords():
"""Get the keywords needed to look up the version information."""
# these strings will be replaced by git during git-archive.
# setup.py/versioneer.py will grep for the variable names, so they must
# each be defined on a line of their own. _version.py will just call
# get_keywords().
git_refnames = "$Format:%d$"
git_full = "$Format:%H$"
git_date = "$Format:%ci$"
keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}
return keywords
class VersioneerConfig:
"""Container for Versioneer configuration parameters."""
def get_config():
"""Create, populate and return the VersioneerConfig() object."""
# these strings are filled in when 'setup.py versioneer' creates
# _version.py
cfg = VersioneerConfig()
cfg.VCS = "git"
cfg.style = "pep440-post"
cfg.tag_prefix = ""
cfg.parentdir_prefix = "None"
cfg.versionfile_source = "wordcloud/_version.py"
cfg.verbose = False
return cfg
class NotThisMethod(Exception):
"""Exception raised if a method is not valid for the current scenario."""
LONG_VERSION_PY = {}
HANDLERS = {}
def register_vcs_handler(vcs, method): # decorator
"""Decorator to mark a method as the handler for a particular VCS."""
def decorate(f):
"""Store f in HANDLERS[vcs][method]."""
if vcs not in HANDLERS:
HANDLERS[vcs] = {}
HANDLERS[vcs][method] = f
return f
return decorate
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
env=None):
"""Call the given command(s)."""
assert isinstance(commands, list)
p = None
for c in commands:
try:
dispcmd = str([c] + args)
# remember shell=False, so use git.cmd on windows, not just git
p = subprocess.Popen([c] + args, cwd=cwd, env=env,
stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr
else None))
break
except EnvironmentError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
if verbose:
print("unable to run %s" % dispcmd)
print(e)
return None, None
else:
if verbose:
print("unable to find command, tried %s" % (commands,))
return None, None
stdout = p.communicate()[0].strip()
if sys.version_info[0] >= 3:
stdout = stdout.decode()
if p.returncode != 0:
if verbose:
print("unable to run %s (error)" % dispcmd)
print("stdout was %s" % stdout)
return None, p.returncode
return stdout, p.returncode
def versions_from_parentdir(parentdir_prefix, root, verbose):
"""Try to determine the version from the parent directory name.
Source tarballs conventionally unpack into a directory that includes both
the project name and a version string. We will also support searching up
two directory levels for an appropriately named parent directory
"""
rootdirs = []
for i in range(3):
dirname = os.path.basename(root)
if dirname.startswith(parentdir_prefix):
return {"version": dirname[len(parentdir_prefix):],
"full-revisionid": None,
"dirty": False, "error": None, "date": None}
else:
rootdirs.append(root)
root = os.path.dirname(root) # up a level
if verbose:
print("Tried directories %s but none started with prefix %s" %
(str(rootdirs), parentdir_prefix))
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
@register_vcs_handler("git", "get_keywords")
def git_get_keywords(versionfile_abs):
"""Extract version information from the given file."""
# the code embedded in _version.py can just fetch the value of these
# keywords. When used from setup.py, we don't want to import _version.py,
# so we do it with a regexp instead. This function is not used from
# _version.py.
keywords = {}
try:
f = open(versionfile_abs, "r")
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["refnames"] = mo.group(1)
if line.strip().startswith("git_full ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["full"] = mo.group(1)
if line.strip().startswith("git_date ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["date"] = mo.group(1)
f.close()
except EnvironmentError:
pass
return keywords
@register_vcs_handler("git", "keywords")
def git_versions_from_keywords(keywords, tag_prefix, verbose):
"""Get version information from git keywords."""
if not keywords:
raise NotThisMethod("no keywords at all, weird")
date = keywords.get("date")
if date is not None:
# git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
# datestamp. However we prefer "%ci" (which expands to an "ISO-8601
# -like" string, which we must then edit to make compliant), because
# it's been around since git-1.5.3, and it's too difficult to
# discover which version we're using, or to work around using an
# older one.
date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
refnames = keywords["refnames"].strip()
if refnames.startswith("$Format"):
if verbose:
print("keywords are unexpanded, not using")
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
refs = set([r.strip() for r in refnames.strip("()").split(",")])
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
TAG = "tag: "
tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
if not tags:
# Either we're using git < 1.8.3, or there really are no tags. We use
# a heuristic: assume all version tags have a digit. The old git %d
# expansion behaves like git log --decorate=short and strips out the
# refs/heads/ and refs/tags/ prefixes that would let us distinguish
# between branches and tags. By ignoring refnames without digits, we
# filter out many common branch names like "release" and
# "stabilization", as well as "HEAD" and "master".
tags = set([r for r in refs if re.search(r'\d', r)])
if verbose:
print("discarding '%s', no digits" % ",".join(refs - tags))
if verbose:
print("likely tags: %s" % ",".join(sorted(tags)))
for ref in sorted(tags):
# sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix):
r = ref[len(tag_prefix):]
if verbose:
print("picking %s" % r)
return {"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": None,
"date": date}
# no suitable tags, so version is "0+unknown", but full hex is still there
if verbose:
print("no suitable tags, using unknown + full revision id")
return {"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": "no suitable tags", "date": None}
@register_vcs_handler("git", "pieces_from_vcs")
def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
"""Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meaning we're inside a checked out source tree.
"""
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root,
hide_stderr=True)
if rc != 0:
if verbose:
print("Directory %s not under git control" % root)
raise NotThisMethod("'git rev-parse --git-dir' returned error")
# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
# if there isn't one, this yields HEX[-dirty] (no NUM)
describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty",
"--always", "--long",
"--match", "%s*" % tag_prefix],
cwd=root)
# --long was added in git-1.5.5
if describe_out is None:
raise NotThisMethod("'git describe' failed")
describe_out = describe_out.strip()
full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
if full_out is None:
raise NotThisMethod("'git rev-parse' failed")
full_out = full_out.strip()
pieces = {}
pieces["long"] = full_out
pieces["short"] = full_out[:7] # maybe improved later
pieces["error"] = None
# parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
# TAG might have hyphens.
git_describe = describe_out
# look for -dirty suffix
dirty = git_describe.endswith("-dirty")
pieces["dirty"] = dirty
if dirty:
git_describe = git_describe[:git_describe.rindex("-dirty")]
# now we have TAG-NUM-gHEX or HEX
if "-" in git_describe:
# TAG-NUM-gHEX
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
if not mo:
# unparseable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%s'"
% describe_out)
return pieces
# tag
full_tag = mo.group(1)
if not full_tag.startswith(tag_prefix):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
% (full_tag, tag_prefix))
return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix):]
# distance: number of commits since tag
pieces["distance"] = int(mo.group(2))
# commit: short hex revision ID
pieces["short"] = mo.group(3)
else:
# HEX: no tags
pieces["closest-tag"] = None
count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"],
cwd=root)
pieces["distance"] = int(count_out) # total number of commits
# commit date: see ISO-8601 comment in git_versions_from_keywords()
date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"],
cwd=root)[0].strip()
pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
return pieces
def plus_or_dot(pieces):
"""Return a + if we don't already have one, else return a ."""
if "+" in pieces.get("closest-tag", ""):
return "."
return "+"
def render_pep440(pieces):
"""Build up version string, with post-release "local version identifier".
Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
Exceptions:
1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += plus_or_dot(pieces)
rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
else:
# exception #1
rendered = "0+untagged.%d.g%s" % (pieces["distance"],
pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
return rendered
def render_pep440_pre(pieces):
"""TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += ".post.dev%d" % pieces["distance"]
else:
# exception #1
rendered = "0.post.dev%d" % pieces["distance"]
return rendered
def render_pep440_post(pieces):
"""TAG[.postDISTANCE[.dev0]+gHEX] .
The ".dev0" means dirty. Note that .dev0 sorts backwards
(a dirty tree will appear "older" than the corresponding clean one),
but you shouldn't be releasing software with -dirty anyways.
Exceptions:
1: no tags. 0.postDISTANCE[.dev0]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += plus_or_dot(pieces)
rendered += "g%s" % pieces["short"]
else:
# exception #1
rendered = "0.post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += "+g%s" % pieces["short"]
return rendered
def render_pep440_old(pieces):
"""TAG[.postDISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.postDISTANCE[.dev0]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
else:
# exception #1
rendered = "0.post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
return rendered
def render_git_describe(pieces):
"""TAG[-DISTANCE-gHEX][-dirty].
Like 'git describe --tags --dirty --always'.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
else:
# exception #1
rendered = pieces["short"]
if pieces["dirty"]:
rendered += "-dirty"
return rendered
def render_git_describe_long(pieces):
"""TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
else:
# exception #1
rendered = pieces["short"]
if pieces["dirty"]:
rendered += "-dirty"
return rendered
def render(pieces, style):
"""Render the given version pieces into the requested style."""
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"],
"date": None}
if not style or style == "default":
style = "pep440" # the default
if style == "pep440":
rendered = render_pep440(pieces)
elif style == "pep440-pre":
rendered = render_pep440_pre(pieces)
elif style == "pep440-post":
rendered = render_pep440_post(pieces)
elif style == "pep440-old":
rendered = render_pep440_old(pieces)
elif style == "git-describe":
rendered = render_git_describe(pieces)
elif style == "git-describe-long":
rendered = render_git_describe_long(pieces)
else:
raise ValueError("unknown style '%s'" % style)
return {"version": rendered, "full-revisionid": pieces["long"],
"dirty": pieces["dirty"], "error": None,
"date": pieces.get("date")}
def get_versions():
"""Get version information or return default if unable to do so."""
# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
# __file__, we can work backwards from there to the root. Some
# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
# case we can only use expanded keywords.
cfg = get_config()
verbose = cfg.verbose
try:
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
verbose)
except NotThisMethod:
pass
try:
root = os.path.realpath(__file__)
# versionfile_source is the relative path from the top of the source
# tree (where the .git directory might live) to this file. Invert
# this to find the root from __file__.
for i in cfg.versionfile_source.split('/'):
root = os.path.dirname(root)
except NameError:
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to find root of source tree",
"date": None}
try:
pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
return render(pieces, cfg.style)
except NotThisMethod:
pass
try:
if cfg.parentdir_prefix:
return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
except NotThisMethod:
pass
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to compute version", "date": None}
| mit | 8751f5c42b874d20a4a210f5dc86dc4c | 34.490385 | 79 | 0.575291 | 3.95436 | false | false | false | false |
materialsproject/custodian | custodian/nwchem/jobs.py | 1 | 2234 | """
This module implements basic kinds of jobs for Nwchem runs.
"""
import shutil
import subprocess
from monty.io import zopen
from monty.shutil import gzip_dir
from custodian.custodian import Job
__author__ = "Shyue Ping Ong"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "ongsp@ucsd.edu"
__status__ = "Beta"
__date__ = "5/20/13"
class NwchemJob(Job):
"""
A basic Nwchem job.
"""
def __init__(
self,
nwchem_cmd,
input_file="mol.nw",
output_file="mol.nwout",
gzipped=False,
backup=True,
settings_override=None,
):
"""
Initializes a basic NwChem job.
Args:
nwchem_cmd ([str]): Command to run Nwchem as a list of args. For
example, ["nwchem"].
input_file (str): Input file to run. Defaults to "mol.nw".
output_file (str): Name of file to direct standard out to.
Defaults to "mol.nwout".
backup (bool): Whether to backup the initial input files. If True,
the input files will be copied with a ".orig" appended.
Defaults to True.
gzipped (bool): Deprecated. Please use the Custodian class's
gzipped_output option instead.
settings_override ([dict]):
An ansible style list of dict to override changes.
#TODO: Not implemented yet.
"""
self.nwchem_cmd = nwchem_cmd
self.input_file = input_file
self.output_file = output_file
self.backup = backup
self.gzipped = gzipped
self.settings_override = settings_override
def setup(self):
"""
Performs backup if necessary.
"""
if self.backup:
shutil.copy(self.input_file, f"{self.input_file}.orig")
def run(self):
"""
Performs actual nwchem run.
"""
with zopen(self.output_file, "w") as fout:
return subprocess.Popen(self.nwchem_cmd + [self.input_file], stdout=fout) # pylint: disable=R1732
def postprocess(self):
"""
Renaming or gzipping as needed.
"""
if self.gzipped:
gzip_dir(".")
| mit | d0397b1c7b4c8c8f9be1a67390ce61f2 | 27.278481 | 110 | 0.561325 | 3.851724 | false | false | false | false |
trolldbois/ctypeslib | ctypeslib/codegen/typehandler.py | 1 | 9685 | """Handler for Type nodes from the clang AST tree."""
from clang.cindex import TypeKind
from ctypeslib.codegen import typedesc
from ctypeslib.codegen.util import log_entity
from ctypeslib.codegen.handler import ClangHandler
from ctypeslib.codegen.handler import InvalidDefinitionError
import logging
log = logging.getLogger('typehandler')
class TypeHandler(ClangHandler):
"""
Handles Cursor Kind and transform them into typedesc.
"""
def __init__(self, parser):
ClangHandler.__init__(self, parser)
self.init_fundamental_types()
def parse_cursor_type(self, _cursor_type):
mth = getattr(self, _cursor_type.kind.name)
return mth(_cursor_type)
##########################################################################
##### TypeKind handlers#######
def init_fundamental_types(self):
"""Registers all fundamental typekind handlers"""
for _id in range(2, 25):
setattr(self, TypeKind.from_id(_id).name,
self._handle_fundamental_types)
def _handle_fundamental_types(self, typ):
"""
Handles POD types nodes.
see init_fundamental_types for the registration.
"""
ctypesname = self.get_ctypes_name(typ.kind)
if typ.kind == TypeKind.VOID:
size = align = 1
else:
size = typ.get_size()
align = typ.get_align()
return typedesc.FundamentalType(ctypesname, size, align)
# INVALID
# OVERLOAD
# DEPENDENT
# OBJCID
# OBJCCLASS
# OBJCSEL
# COMPLEX
# BLOCKPOINTER
# LVALUEREFERENCE
# RVALUEREFERENCE
# OBJCINTERFACE
# OBJCOBJECTPOINTER
# FUNCTIONNOPROTO
# FUNCTIONPROTO
# VECTOR
# MEMBERPOINTER
## const, restrict and volatile
## typedesc.CvQualifiedType(typ, const, volatile)
# Type has multiple functions for const, volatile, restrict
# not listed has node in the AST.
# not very useful in python anyway.
@log_entity
def TYPEDEF(self, _cursor_type):
"""
Handles TYPEDEF statement.
"""
_decl = _cursor_type.get_declaration()
name = self.get_unique_name(_decl)
if self.is_registered(name):
obj = self.get_registered(name)
else:
log.debug('Was in TYPEDEF but had to parse record declaration for %s', name)
obj = self.parse_cursor(_decl)
return obj
@log_entity
def ENUM(self, _cursor_type):
"""
Handles ENUM typedef.
"""
_decl = _cursor_type.get_declaration()
name = self.get_unique_name(_decl)
if self.is_registered(name):
obj = self.get_registered(name)
else:
log.warning('Was in ENUM but had to parse record declaration ')
obj = self.parse_cursor(_decl)
return obj
@log_entity
def ELABORATED(self, _cursor_type):
"""
Handles elaborated types eg. enum return.
"""
_decl = _cursor_type.get_declaration()
name = self.get_unique_name(_decl)
if self.is_registered(name):
obj = self.get_registered(name)
else:
log.warning('Was in ELABORATED but had to parse record declaration ')
obj = self.parse_cursor(_decl)
return obj
@log_entity
def POINTER(self, _cursor_type):
"""
Handles POINTER types.
"""
#
# FIXME catch InvalidDefinitionError and return a void *
#
#
# we shortcut to canonical typedefs and to pointee canonical defs
comment = None
_type = _cursor_type.get_pointee().get_canonical()
_p_type_name = self.get_unique_name(_type)
# get pointer size
size = _cursor_type.get_size() # not size of pointee
align = _cursor_type.get_align()
log.debug(
"POINTER: size:%d align:%d typ:%s",
size, align, _type.kind)
if self.is_fundamental_type(_type):
p_type = self.parse_cursor_type(_type)
elif self.is_pointer_type(_type) or self.is_array_type(_type):
p_type = self.parse_cursor_type(_type)
elif _type.kind == TypeKind.FUNCTIONPROTO:
p_type = self.parse_cursor_type(_type)
elif _type.kind == TypeKind.FUNCTIONNOPROTO:
p_type = self.parse_cursor_type(_type)
else: # elif _type.kind == TypeKind.RECORD:
# check registration
decl = _type.get_declaration()
decl_name = self.get_unique_name(decl)
# Type is already defined OR will be defined later.
if self.is_registered(decl_name):
p_type = self.get_registered(decl_name)
else: # forward declaration, without looping
log.debug(
'POINTER: %s type was not previously declared',
decl_name)
try:
p_type = self.parse_cursor(decl)
except InvalidDefinitionError as e:
# no declaration in source file. Fake a void *
p_type = typedesc.FundamentalType('None', 1, 1)
comment = "InvalidDefinitionError"
log.debug("POINTER: pointee type_name:'%s'", _p_type_name)
# return the pointer
obj = typedesc.PointerType(p_type, size, align)
obj.location = p_type.location
if comment is not None:
obj.comment = comment
return obj
@log_entity
def _array_handler(self, _cursor_type):
"""
Handles all array types.
Resolves it's element type and makes a Array typedesc.
"""
# The element type has been previously declared
# we need to get the canonical typedef, in some cases
_type = _cursor_type.get_canonical()
size = _type.get_array_size()
if size == -1 and _type.kind == TypeKind.INCOMPLETEARRAY:
size = 0
# FIXME: Incomplete Array handling at end of record.
# https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html
# FIXME VARIABLEARRAY DEPENDENTSIZEDARRAY
_array_type = _type.get_array_element_type() # .get_canonical()
if self.is_fundamental_type(_array_type):
_subtype = self.parse_cursor_type(_array_type)
elif self.is_pointer_type(_array_type):
# code.interact(local=locals())
# pointers to POD have no declaration ??
# FIXME test_struct_with_pointer x_n_t g[1]
_subtype = self.parse_cursor_type(_array_type)
elif self.is_array_type(_array_type):
_subtype = self.parse_cursor_type(_array_type)
else:
_subtype_decl = _array_type.get_declaration()
_subtype = self.parse_cursor(_subtype_decl)
# if _subtype_decl.kind == CursorKind.NO_DECL_FOUND:
# pass
#_subtype_name = self.get_unique_name(_subtype_decl)
#_subtype = self.get_registered(_subtype_name)
obj = typedesc.ArrayType(_subtype, size)
obj.location = _subtype.location
return obj
CONSTANTARRAY = _array_handler
INCOMPLETEARRAY = _array_handler
VARIABLEARRAY = _array_handler
DEPENDENTSIZEDARRAY = _array_handler
@log_entity
def FUNCTIONPROTO(self, _cursor_type):
"""Handles function prototype."""
# id, returns, attributes
returns = _cursor_type.get_result()
# if self.is_fundamental_type(returns):
returns = self.parse_cursor_type(returns)
attributes = []
obj = typedesc.FunctionType(returns, attributes)
for i, _attr_type in enumerate(_cursor_type.argument_types()):
arg = typedesc.Argument(
"a%d" %
(i),
self.parse_cursor_type(_attr_type))
obj.add_argument(arg)
self.set_location(obj, None)
return obj
@log_entity
def FUNCTIONNOPROTO(self, _cursor_type):
"""Handles function with no prototype."""
# id, returns, attributes
returns = _cursor_type.get_result()
# if self.is_fundamental_type(returns):
returns = self.parse_cursor_type(returns)
attributes = []
obj = typedesc.FunctionType(returns, attributes)
# argument_types cant be asked. no arguments.
self.set_location(obj, None)
return obj
# structures, unions, classes
@log_entity
def RECORD(self, _cursor_type):
"""
A record is a NOT a declaration. A record is the occurrence of of
previously defined record type. So no action is needed. Type is already
known.
Type is accessible by cursor.type.get_declaration()
"""
_decl = _cursor_type.get_declaration() # is a record
# code.interact(local=locals())
#_decl_cursor = list(_decl.get_children())[0] # record -> decl
name = self.get_unique_name(_decl) # _cursor)
if self.is_registered(name):
obj = self.get_registered(name)
else:
log.debug('Was in RECORD but had to parse record declaration for %s',name)
obj = self.parse_cursor(_decl)
return obj
@log_entity
def UNEXPOSED(self, _cursor_type):
"""
Handles unexposed types.
Returns the canonical type instead.
"""
_decl = _cursor_type.get_declaration()
name = self.get_unique_name(_decl) # _cursor)
if self.is_registered(name):
obj = self.get_registered(name)
else:
obj = self.parse_cursor(_decl)
return obj
| mit | 8003ffe01e889634d8a063b8981a7826 | 34.606618 | 88 | 0.579659 | 3.951448 | false | false | false | false |
phetsims/phet-info | ide/sublime-text/phet-plugin/phet.py | 1 | 28099 | # Copyright 2020, University of Colorado Boulder
#
# @author Jonathan Olson <jonathan.olson@colorado.edu>
import sublime, sublime_plugin, os, re, subprocess, webbrowser, json, threading
from functools import reduce
# Useful URLs:
# https://www.sublimetext.com/docs/3/api_reference.html
# http://www.sublimetext.com/docs/commands
# https://github.com/Binocular222/Sublime-Text-3-Full-Documentation
# https://github.com/Binocular222/Sublime-Text-3-Full-Documentation/blob/master/Command.txt
# https://www.sublimetext.com/docs/3/scope_naming.html
# https://sublime-text-unofficial-documentation.readthedocs.io/en/latest/reference/api.html
# undocumented APIs?:
# [func for func in dir(sublime.View) if callable(getattr(sublime.View, func))]
# [func for func in dir(sublime.Window) if callable(getattr(sublime.View, func))]
# lookup_references_in_index / lookup_references_in_open_files / lookup_symbol_in_index / lookup_symbol_in_open_files
# [func for func in dir(sublime) if callable(getattr(sublime.View, func))]
# potential commands?
# auto_complete build clear_fields close_file copy cut decrease_font_size delete_word duplicate_line exec
# expand_selection find_all_under find_next find_prev find_under find_under_expand find_under_prev focus_group
# hide_auto_complete hide_overlay hide_panel increase_font_size indent insert insert_snippet join_lines left_delete move
# move_to move_to_group new_file new_window next_field next_result next_view next_view_in_stack paste paste_and_indent
# prev_field prev_result prev_view prev_view_in_stack prompt_open_file prompt_save_as prompt_select_project redo
# redo_or_repeat reindent right_delete run_macro run_macro_file save scroll_lines select_all select_lines set_layout
# show_overlay show_panel show_scope_name single_selection slurp_find_string slurp_replace_string soft_redo soft_undo
# sort_lines split_selection_into_lines swap_line_down swap_line_up switch_file toggle_comment toggle_full_screen
# toggle_overwrite toggle_record_macro toggle_side_bar transpose undo unindent
# >>> view.extract_completions( 'updateS' )
# ['updateSize', 'updateStepInformation']
# >>> view.indentation_level( view.sel()[0].begin() )
# 2
# view.substr(view.indented_region( view.sel()[0].begin() ))
# >>> view.indexed_references()
# [((798, 803), 'merge'), ((826, 844), 'createFromVertices'), ((856, 876), 'getEllipsoidVertices'), ((937, 954), 'getEllipsoidShape'), ((1007, 1016), 'getVolume'), ((1100, 1106), 'assert'), ((1339, 1349), 'updateSize'), ((1500, 1518), 'updateFromVertices'), ((1541, 1561), 'getEllipsoidVertices'), ((1676, 1693), 'getEllipsoidShape'), ((1764, 1773), 'getVolume'), ((2571, 2581), 'updateSize'), ((2593, 2610), 'getSizeFromRatios'), ((2690, 2716), 'bodyGetStepMatrixTransform'), ((2785, 2788), 'm02'), ((2828, 2831), 'm12'), ((3767, 3781), 'getTranslation'), ((3784, 3793), 'toVector3'), ((3881, 3889), 'minusXYZ'), ((4703, 4726), 'solveQuadraticRootsReal'), ((4738, 4744), 'filter'), ((6232, 6237), 'reset'), ((6250, 6260), 'updateSize'), ((6300, 6305), 'reset'), ((6516, 6523), 'ellipse'), ((6926, 6930), 'push'), ((6950, 6953), 'cos'), ((6981, 6984), 'sin'), ((7329, 7337), 'register')]
# >>> view.indexed_symbols()
# [((625, 634), 'Ellipsoid'), ((747, 758), 'constructor'), ((1463, 1473), 'updateSize'), ((2161, 2178), 'getSizeFromRatios'), ((2523, 2532), 'setRatios'), ((2648, 2669), 'updateStepInformation'), ((3703, 3712), 'intersect'), ((5097, 5113), 'getDisplacedArea'), ((5706, 5724), 'getDisplacedVolume'), ((6200, 6205), 'reset'), ((6462, 6479), 'getEllipsoidShape'), ((6729, 6749), 'getEllipsoidVertices'), ((7216, 7225), 'getVolume')]
# for temp files:
# def get_cache_directory():
# path = os.path.join(sublime.cache_path(), 'phet')
# if not os.path.exists(path):
# os.mkdir(path)
# return path
# sublime.log_commands(True)
# sublime.log_commands(False)
linesep = os.linesep
pathsep = os.path.sep
goto_region_dict = {}
def clear_goto_region(id):
goto_region_dict[id] = []
def push_goto_region(id, from_region, to_file, to):
if id not in goto_region_dict:
clear_goto_region(id)
goto_region_dict[id].append({'from_region': from_region, 'to_file': to_file, 'to': to})
def lookup_goto_region(id, point):
if id not in goto_region_dict:
return None
for entry in goto_region_dict[id]:
from_region = entry['from_region']
if point > from_region.begin() and point < from_region.end():
return entry
load_actions = {}
number_names = [ 'i', 'j', 'n', 'x', 'y', 'z', 'width', 'height', 'index', 'dt' ]
node_names = [ 'node', 'content', 'listParent' ]
def detect_type(name):
"""Returns a guess on the type of a given name"""
if name in number_names:
return 'number'
if name.endswith('Node') or name in node_names:
return 'Node'
if name.endswith('Bounds') or name == 'bounds':
return 'Bounds2'
if name.endswith('Point') or name == 'point':
return 'Vector2'
if name.endswith('Position') or name == 'position':
return 'Vector2'
if name.endswith('Property') or name == 'property':
return 'Property.<*>'
if name == 'options':
return '[Object]'
if name == 'config':
return 'Object'
if name == 'tandem':
return 'Tandem'
return '*'
def execute(cmd, cmd_args, cwd, callback):
def thread_target(cmd, cmd_args, cwd, callback):
proc = subprocess.Popen([ cmd ] + cmd_args, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# proc.wait()
callback(proc.communicate()[0].decode())
thread = threading.Thread(target=thread_target, args=(cmd, cmd_args, cwd, callback))
thread.start()
# returns immediately after the thread starts
return thread
def execute_and_show(view, cmd, cmd_args, cwd):
execute(cmd, cmd_args, cwd, lambda output: show_output(view.window(), output))
def open_link(url):
webbrowser.get('chrome').open(url, autoraise=True)
def show_output(window, str):
view = window.create_output_panel('phet')
view.set_read_only(False)
view.run_command('append', {"characters": str})
view.set_read_only(True)
window.run_command('show_panel', {"panel": "output.phet"})
def get_git_root(view):
"""Returns the absolute path of the git root"""
return view.window().folders()[0]
def get_relative_to_root(view, path):
return os.path.relpath(path, get_git_root(view))
def path_split(path):
splits = os.path.split(path)
if splits[0]:
return path_split(splits[0]) + [splits[1]]
else:
return [splits[1]]
def get_repo(view):
relative_path = get_relative_to_root(view, view.file_name())
if relative_path[0] == '.':
return None
else:
return path_split(relative_path)[0]
def count_up_directory(path):
"""Returns a count of ../, for determining what the best path is to import"""
return path.count('../')
def union_regions(regions):
"""Returns the union of sublime.Region instances (using their term 'cover')"""
return reduce((lambda maybe,region: region if maybe == None else maybe.cover(region)),regions,None)
def expand_region(region, str, num_lines):
begin = region.begin()
end = region.end()
# TODO: Windows?
# expand to the line
begin = str.rfind('\n', 0, begin) + 1
end = str.find('\n', end, len(str))
for x in range(num_lines):
if begin > 1:
begin = str.rfind('\n', 0, begin - 2 ) + 1
if end < len(str) - 1 and end != -1:
end = str.find('\n', end + 1, len(str))
if begin == -1:
begin = 0
if end == -1:
end = len(str)
return sublime.Region(begin, end)
def collapse_expanded_regions(regions, str, num_lines):
current = None
result = []
for region in regions:
expanded_region = expand_region(region, str, num_lines)
if current:
if current['expanded_region'].intersects(expanded_region):
current['expanded_region'] = current['expanded_region'].cover(expanded_region)
current['regions'].append(region)
else:
result.append(current)
current = {'expanded_region': expanded_region, 'regions': [region]}
else:
current = {'expanded_region': expanded_region, 'regions': [region]}
if current:
result.append(current)
return result
def is_node_js(view):
"""Whether we're handling things in a node.js or module context"""
return (not view.find('\n\'use strict\';\n', 0).empty()) and (not view.find(' = require\\( \'', 0).empty())
def load_file(path):
"""Loads a file as a string"""
with open(path, 'r', encoding='utf8') as content_file:
content = content_file.read()
return content
def get_build_local():
return json.loads(load_file(os.path.expanduser('~') + '/.phet/build-local.json'))
def get_local_testing_url():
return get_build_local()[ 'localTestingURL' ]
def handle_windows_relative_path(path):
return path.replace('\\', '/')
def ensure_dot_slash(path):
if path[0] != '.':
return './' + path
return path
def get_perennial_list(view, name):
"""Ability to load things like active-repos with e.g. get_perennial_list(view, 'active-repos')"""
return list(filter(lambda line: len(line) > 0, load_file(os.path.join(get_git_root(view),'perennial/data/' + name)).splitlines()))
def get_active_repos(view):
return get_perennial_list(view, 'active-repos')
def scan_for_relative_js_files(view, js_type_name):
"""Walks our filesystem of repo/js/** looking for something matching ${js_type_name}.js, returned as relative paths"""
results = []
current_path = os.path.dirname(view.file_name())
for repo in get_active_repos(view):
repo_path = os.path.join(get_git_root(view), repo + '/js')
for root, dirs, files in os.walk(repo_path):
for name in files:
if name == js_type_name + '.js':
results.append(os.path.join(root, name))
return list(map(handle_windows_relative_path, map(lambda x: os.path.relpath(x, current_path), results)))
def lookup_import_paths(view, str):
"""Returns a list of relative paths for modules detected to str"""
current_path = os.path.dirname(view.file_name())
locations = list(filter(lambda x: (str + '.js') in x[0] and not ('blue-rain' in x[0]), view.window().lookup_symbol_in_index(str)))
return list(map(handle_windows_relative_path, map(lambda x: os.path.relpath(x[0], current_path), locations)))
def filter_preferred_paths(paths):
"""Returns all paths with the same minimum count of ../ in them"""
min_directory_up_count = min(map(count_up_directory,paths))
return filter(lambda path: count_up_directory(path) == min_directory_up_count, paths)
def contains_import(view, str):
if is_node_js(view):
return not view.find('const ' + str + ' = require\\(', 0).empty()
else:
return not view.find('import ' + str, 0).empty()
def find_import_regions(view):
if is_node_js(view):
return view.find_all(r'^const .+ = require\(.+;.*$');
else:
return view.find_all(r'^import .+;$');
def sort_imports(view, edit):
import_regions = find_import_regions(view)
start_index = union_regions(import_regions).begin()
import_strings = []
for region in reversed(import_regions):
import_strings.append(view.substr(region))
view.erase(edit,view.full_line(region))
# It should work to sort imports after the first apostrophe for both node.js and modules
for import_string in sorted(import_strings,key=(lambda str: str.split('\'')[1]), reverse=True):
view.insert(edit, start_index, import_string + '\n')
def remove_unused_imports(view, edit):
"""Removes imports where their declared string isn't in the file (not 100% accurate, but helpful)"""
candidate_regions = find_import_regions(view)
regions_to_remove = []
after_imports_point = union_regions(candidate_regions).end()
for region in candidate_regions:
import_string = view.substr(region)
if import_string.startswith('const '):
name = import_string.split(' ')[1]
elif import_string.startswith('import '):
match = re.search('import (.+) from', import_string)
if match:
name = match.group(1)
else:
break
else:
break
if view.find(name, after_imports_point).empty():
regions_to_remove.append(region)
# iterate backward so we don't have to recompute regions here
for region in reversed(regions_to_remove):
print('removing: ' + view.substr(region))
view.erase(edit,view.full_line(region))
def insert_import_in_front(view, edit, import_text):
start_index = union_regions(find_import_regions(view)).begin()
view.insert(edit, start_index, import_text + '\n')
def insert_import_and_sort(view, edit, name, path):
if is_node_js(view):
# strip off .js suffix
if path.endswith( '.js' ):
path = path[:-3]
insert_import_in_front(view, edit, 'const ' + name + ' = require( \'' + path +'\' );')
else:
insert_import_in_front(view, edit, 'import ' + name + ' from \'' + path +'\';')
sort_imports(view, edit)
def try_import_name(name, view, edit):
if not contains_import(view, name):
# scan for symbols in a fast way (with known files in the Sublime index)
paths = lookup_import_paths(view, name)
# fall back to scanning all JS files we have, use their names
if not paths:
paths = scan_for_relative_js_files(view, name)
paths = list(map(ensure_dot_slash, paths))
# if we're in node.js mode, we want to be able to import built-ins or top-level things like 'fs', which probably
# will not be found
if is_node_js(view) and not paths:
paths = [name + '.js'] # the suffix will get stripped off later
if paths:
# find preferred paths (smallest amounts of ../)
paths = list(filter_preferred_paths(paths))
# we'll need to show a popup if there are still multiple choices
if len(paths) == 1:
insert_import_and_sort(view, edit, name, paths[0])
else:
# if we hit escape, don't error out or try to import something
def on_done(index):
if index >= 0:
view.run_command('phet_internal_import', {"name": name, "path": paths[index]})
view.window().show_quick_panel(paths, on_done)
else:
view.window().status_message('could not find: ' + name)
else:
view.window().status_message('contains import for: ' + name)
def show_lint_output(output):
lines = output.splitlines()
output_view = sublime.active_window().create_output_panel('phetlint')
clear_goto_region(output_view.id())
current_file = None
for line in lines:
match = re.search('^ +([0-9]+):([0-9]+)', line )
if len(line) > 0 and line[0] == '/':
current_file = line
output_view.run_command('phet_internal_append_result', {'str': line + '\n'})
elif match:
row = int(match.group(1)) - 1
col = int(match.group(2)) - 1
output_view.run_command('phet_internal_append_search_result_row_col', {'str': line, 'to_file': current_file, 'row': row, 'col': col})
output_view.run_command('phet_internal_append_result', {'str': '\n'})
else:
output_view.run_command('phet_internal_append_result', {'str': line + '\n'})
sublime.active_window().run_command('show_panel', {"panel": "output.phetlint"})
abort_search = False
def threaded_for_js_files(repos, git_root, on_path, on_done):
def thread_target(repos, git_root, on_path, on_done):
global abort_search
for repo in repos:
# TODO: git root should be a setting? or get from the active window instead
repo_path = os.path.join(git_root, repo + '/js')
for root, dirs, files in os.walk(repo_path):
is_phet_io_dir = 'js/phet-io' in root
for name in files:
if '-baseline.js' in name or '-overrides.js' in name or '-types.js' in name:
continue
path = os.path.join(root, name)
if abort_search:
abort_search = True
return
on_path(path)
on_done()
thread = threading.Thread(target=thread_target, args=(repos, git_root, on_path, on_done))
thread.start()
# returns immediately after the thread starts
return thread
class PhetInternalImportCommand(sublime_plugin.TextCommand):
def run(self, edit, name, path):
view = self.view
insert_import_and_sort(self.view, edit, name, path)
class PhetInternalGoToRepoCommand(sublime_plugin.TextCommand):
def run(self, edit, repo):
view = self.view
view.window().open_file(get_git_root(view) + '/' + repo + '/README.md', sublime.TRANSIENT)
class PhetInternalAppendResult(sublime_plugin.TextCommand):
def run(self, edit, str):
view = self.view
view.set_read_only(False)
view.insert(edit, view.size(), str)
view.set_read_only(True)
class PhetInternalAppendSearchResultRegion(sublime_plugin.TextCommand):
def run(self, edit, str, to_file, start_index, end_index):
view = self.view
view.set_read_only(False)
start = view.size()
view.insert(edit, start, str)
end = view.size()
find_region = sublime.Region(start, end)
view.add_regions('phet_find_result', view.get_regions('phet_find_result') + [find_region], 'string')
view.set_read_only(True)
push_goto_region(view.id(), find_region, to_file, sublime.Region(start_index, end_index))
class PhetInternalAppendSearchResultRowCol(sublime_plugin.TextCommand):
def run(self, edit, str, to_file, row, col):
view = self.view
view.set_read_only(False)
start = view.size()
view.insert(edit, start, str)
end = view.size()
find_region = sublime.Region(start, end)
# TODO: set our own sytax and colors, but for now just borrow this
# view.add_regions('phet_find_result', view.get_regions('phet_find_result') + [find_region], 'string', flags=(sublime.DRAW_NO_FILL))
view.add_regions('phet_find_result', view.get_regions('phet_find_result') + [find_region], 'string')
# view.add_regions('phet_find_result', view.get_regions('phet_find_result') + [find_region], 'constant')
# view.add_regions('phet_find_result', view.get_regions('phet_find_result') + [find_region], 'keyword')
view.set_read_only(True)
push_goto_region(view.id(), find_region, to_file, (row, col))
class PhetInternalSearch(sublime_plugin.TextCommand):
def run(self, edit, pattern):
view = self.view
output_view = sublime.active_window().create_output_panel('phetfind')
output_view.set_syntax_file('Packages/phet-plugin/phet-find-results.tmLanguage')
clear_goto_region(output_view.id())
output_view.run_command('phet_internal_append_result', {'str': 'Searching...\n\n'})
sublime.active_window().run_command('show_panel', {"panel": "output.phetfind"})
expr = re.compile(pattern)
def regions_from_string(str):
regions = []
for match in expr.finditer(str):
regions.append(sublime.Region(match.start(), match.end()))
return regions
def on_path(path):
file_string = load_file(path)
regions = regions_from_string(file_string)
if regions:
# TODO windows
display_name = path[path.rfind('/')+1:]
if '.js' in display_name:
display_name = display_name[:display_name.find('.js')]
output_view.run_command('phet_internal_append_result', {'str': display_name + ' ' + path + ':\n\n'})
expanded_region_data = collapse_expanded_regions(regions, file_string, 2)
for entry in expanded_region_data:
expanded_region = entry['expanded_region']
sub_regions = entry['regions']
if sub_regions[0].begin() > expanded_region.begin():
output_view.run_command('phet_internal_append_result', {'str': file_string[expanded_region.begin():sub_regions[0].begin()]})
for i in range(len(sub_regions)):
sub_region = sub_regions[i]
output_view.run_command('phet_internal_append_search_result_region', {'str': file_string[sub_region.begin():sub_region.end()], 'to_file': path, 'start_index': sub_region.begin(), 'end_index': sub_region.end()})
if i + 1 < len(sub_regions):
next_sub_region = sub_regions[i + 1]
if sub_region.end() < next_sub_region.begin():
output_view.run_command('phet_internal_append_result', {'str': file_string[sub_region.end():next_sub_region.begin()]})
last_sub_region = sub_regions[len(sub_regions) - 1]
if last_sub_region.end() < expanded_region.end():
output_view.run_command('phet_internal_append_result', {'str': file_string[last_sub_region.end():expanded_region.end()]})
output_view.run_command('phet_internal_append_result', {'str': '\n\n'})
def on_done():
output_view.run_command('phet_internal_append_result', {'str': 'Done\n'})
repos = get_active_repos(view)
preferred_repo = get_repo(view)
repos.remove(preferred_repo)
repos.insert(0, preferred_repo)
threaded_for_js_files(repos, get_git_root(view), on_path, on_done)
class PhetDevCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
print(get_repo(view))
class PhetFindCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
if len(view.sel()):
view.run_command('phet_internal_search', {'pattern': re.escape(view.substr(view.word(view.sel()[0])))})
class PhetFindRegexCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
def on_done(str):
view.run_command('phet_internal_search', {'pattern': str})
view.window().show_input_panel('Find regex', '', on_done, None, None)
class PhetShowFindCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
sublime.active_window().run_command('show_panel', {"panel": "output.phetfind"})
class PhetWipeFindCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
output_view = sublime.active_window().create_output_panel('phetfind')
output_view.erase(edit, sublime.Region(0,output_view.size()))
clear_goto_region(output_view.id())
class PhetAbortFindCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
abort_search = True;
output_view = sublime.active_window().create_output_panel('phetfind')
output_view.erase(edit, sublime.Region(0,output_view.size()))
clear_goto_region(output_view.id())
class PhetLintCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
repo = get_repo(view)
if repo:
execute('grunt', ['lint', '--no-color'], get_git_root(view) + '/' + repo, show_lint_output)
class PhetLintEverythingCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
execute('grunt', ['lint-everything', '--no-color'], get_git_root(view) + '/perennial', show_lint_output)
class PhetUpdateCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
repo = get_repo(view)
if repo:
execute_and_show(view, 'grunt', ['update', '--no-color'], get_git_root(view) + '/' + repo)
class PhetGruntCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
repo = get_repo(view)
if repo:
execute_and_show(view, 'grunt', ['--no-color'], get_git_root(view) + '/' + repo)
class PhetImportCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
for region in view.sel():
# get the name we're trying to import
name = view.substr(view.word(region))
try_import_name(name, view, edit)
class PhetCleanCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
remove_unused_imports(view, edit)
sort_imports(view, edit)
class PhetSortImportsCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
sort_imports(view, edit)
class PhetRemoveUnusedImportsCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
remove_unused_imports(view, edit)
class PhetDocumentFunction(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
for region in view.sel():
start_point = region.begin()
name_region = view.word(region)
name = view.substr(name_region)
previous_line_point = view.full_line(name_region).begin() - 1
name_scope_region = view.extract_scope(start_point)
name_and_parameters = view.substr(view.extract_scope(name_scope_region.end()))
function_scope_region = view.extract_scope(view.full_line(name_scope_region).end() + 1)
indentation = view.indentation_level( start_point )
hasReturn = 'return' in view.substr(function_scope_region)
parameters = []
paren_start = name_and_parameters.find('( ')
paren_end = name_and_parameters.find(' )')
if paren_start >= 0 and paren_end >= 0:
# todo: handle defaults?
parameters = name_and_parameters[paren_start + 2 : paren_end].split( ', ' )
whitespace = indentation * ' '
comment = '\n' + whitespace + '/**\n' + whitespace + ' * '
if name == 'dispose':
comment = comment + 'Releases references\n' + whitespace + ' * @public'
if name == 'step':
comment = comment + 'Steps forward in time\n' + whitespace + ' * @public'
comment = comment + '\n'
if parameters:
comment = comment + whitespace + ' *\n'
for parameter in parameters:
# todo: guess type
comment = comment + whitespace + ' * @param {' + detect_type(parameter) + '} ' + parameter + '\n'
if hasReturn:
comment = comment + whitespace + ' * @returns {*}\n'
comment = comment + whitespace + ' */'
view.insert(edit, previous_line_point, comment)
class PhetOpenPhetmarksCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
open_link(get_local_testing_url() + 'phetmarks')
class PhetOpenGithubCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
repo = get_repo(view)
if repo:
open_link('https://github.com/phetsims/' + repo)
class PhetOpenIssuesCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
repo = get_repo(view)
if repo:
open_link('https://github.com/phetsims/' + repo + '/issues')
class PhetOpenSimCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
repo = get_repo(view)
if repo:
open_link(get_local_testing_url() + repo + '/' + repo + '_en.html?ea&brand=phet')
class PhetOpenBuiltSimCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
repo = get_repo(view)
if repo:
open_link(get_local_testing_url() + repo + '/build/phet/' + repo + '_en_phet.html')
class PhetGoToRepoCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
active_repos = get_active_repos(view)
# if we hit escape, don't error out or try to import something
def on_done(index):
if index >= 0:
view.run_command('phet_internal_go_to_repo', {"repo": active_repos[index]})
view.window().show_quick_panel(active_repos, on_done)
class PhetEventListener(sublime_plugin.EventListener):
def on_load(self, view):
id = view.id()
if id in load_actions:
load_actions[id]()
del load_actions[id]
def on_selection_modified_async(self, view):
for region in view.sel():
entry = lookup_goto_region(view.id(), region.begin())
if entry:
new_view = sublime.active_window().open_file(entry['to_file'], sublime.TRANSIENT)
def on_loaded():
to = entry['to']
if isinstance(to, sublime.Region):
to_region = to
else:
point = new_view.text_point(to[0], to[1])
to_region = sublime.Region(point, point)
new_view.sel().clear()
new_view.sel().add(to_region)
if new_view.window():
new_view.window().focus_view(new_view)
new_view.window().run_command('focus_neighboring_group')
sublime.active_window().focus_view(new_view)
sublime.set_timeout(lambda: new_view.window().focus_view(new_view), 10)
new_view.show_at_center(to_region)
if new_view.is_loading():
load_actions[new_view.id()] = on_loaded
else:
on_loaded()
| mit | 9fb03675061449835a939d7072784689 | 37.810773 | 887 | 0.65892 | 3.256722 | false | false | false | false |
devopshq/crosspm | crosspm/adapters/files.py | 1 | 11118 | # -*- coding: utf-8 -*-
import json
import shutil
import pathlib
from crosspm.adapters.common import BaseAdapter
from crosspm.helpers.exceptions import * # noqa
from crosspm.helpers.package import Package
from crosspm.helpers.config import CROSSPM_DEPENDENCY_LOCK_FILENAME
import os
CHUNK_SIZE = 1024
setup = {
"name": [
"files",
],
}
# class PureFilesPath(pathlib.PurePath):
# """
# A class to work with Files paths that doesn't connect
# to any server. I.e. it supports only basic path
# operations.
# """
# _flavour = pathlib._posix_flavour
# __slots__ = ()
#
class FilesPath(pathlib.Path): # , PureFilesPath):
def glob(self, pattern):
return super(FilesPath, self).glob(pattern)
def rglob(self, pattern):
return super(FilesPath, self).rglob(pattern)
def __new__(cls, *args, **kwargs):
cls = WindowsPath if os.name == 'nt' else PosixPath
obj = pathlib.Path.__new__(cls, *args, **kwargs)
return obj
@property
def properties(self):
"""
Fetch artifact properties
"""
return {}
@properties.setter
def properties(self, properties):
self.del_properties(self.properties, recursive=False)
self.set_properties(properties, recursive=False)
@properties.deleter
def properties(self):
self.del_properties(self.properties, recursive=False)
def set_properties(self, properties, recursive=True):
"""
Adds new or modifies existing properties listed in properties
properties - is a dict which contains the property names and values to set.
Property values can be a list or tuple to set multiple values
for a key.
recursive - on folders property attachment is recursive by default. It is
possible to force recursive behavior.
"""
if not properties:
return False
return True # self._accessor.set_properties(self, properties, recursive)
def del_properties(self, properties, recursive=None):
"""
Delete properties listed in properties
properties - iterable contains the property names to delete. If it is an
str it will be casted to tuple.
recursive - on folders property attachment is recursive by default. It is
possible to force recursive behavior.
"""
return True # self._accessor.del_properties(self, properties, recursive)
class PosixPath(FilesPath, pathlib.PurePosixPath):
__slots__ = ()
class WindowsPath(FilesPath, pathlib.PureWindowsPath):
__slots__ = ()
def owner(self):
raise NotImplementedError("Path.owner() is unsupported on this system")
def group(self):
raise NotImplementedError("Path.group() is unsupported on this system")
class Adapter(BaseAdapter):
def get_packages(self, source, parser, downloader, list_or_file_path):
_pkg_name_col = self._config.name_column
_packages_found = {}
_pkg_name_old = ""
for _paths in parser.get_paths(list_or_file_path, source):
_packages = []
_params_found = {}
_params_found_raw = {}
last_error = ''
_pkg_name = _paths['params'][_pkg_name_col]
if _pkg_name != _pkg_name_old:
_pkg_name_old = _pkg_name
self._log.info(
'{}: {}'.format(_pkg_name,
{k: v for k, v in _paths['params'].items() if
k not in (_pkg_name_col, 'repo')}))
for _sub_paths in _paths['paths']:
self._log.info('repo: {}'.format(_sub_paths['repo']))
for _path in _sub_paths['paths']:
_tmp_params = dict(_paths['params'])
_tmp_params['repo'] = _sub_paths['repo']
_path_fixed, _path_pattern = parser.split_fixed_pattern(_path)
_repo_paths = FilesPath(_path_fixed)
try:
for _repo_path in _repo_paths.glob(_path_pattern):
_mark = 'found'
_matched, _params, _params_raw = parser.validate_path(str(_repo_path), _tmp_params)
if _matched:
_params_found[_repo_path] = {k: v for k, v in _params.items()}
_params_found_raw[_repo_path] = {k: v for k, v in _params_raw.items()}
_mark = 'match'
_valid, _params = parser.validate(_repo_path.properties, 'properties', _tmp_params,
return_params=True)
if _valid:
_mark = 'valid'
_packages += [_repo_path]
_params_found[_repo_path].update({k: v for k, v in _params.items()})
_params_found[_repo_path]['filename'] = str(_repo_path.name)
self._log.debug(' {}: {}'.format(_mark, str(_repo_path)))
except RuntimeError as e:
try:
err = json.loads(e.args[0])
except Exception:
err = {}
if isinstance(err, dict):
# TODO: Check errors
# e.args[0] = '''{
# "errors" : [ {
# "status" : 404,
# "message" : "Not Found"
# } ]
# }'''
for error in err.get('errors', []):
err_status = error.get('status', -1)
err_msg = error.get('message', '')
if err_status == 401:
msg = 'Authentication error[{}]{}'.format(err_status,
(': {}'.format(
err_msg)) if err_msg else '')
elif err_status == 404:
msg = last_error
else:
msg = 'Error[{}]{}'.format(err_status,
(': {}'.format(err_msg)) if err_msg else '')
if last_error != msg:
self._log.error(msg)
last_error = msg
_package = None
if _packages:
_packages = parser.filter_one(_packages, _paths['params'], _params_found)
if isinstance(_packages, dict):
_packages = [_packages]
if len(_packages) == 1:
_stat_pkg = self.pkg_stat(_packages[0]['path'])
_params_raw = _params_found_raw.get(_packages[0]['path'], {})
_params_tmp = _params_found.get(_packages[0]['path'], {})
_params_tmp.update({k: v for k, v in _packages[0]['params'].items() if k not in _params_tmp})
_package = Package(_pkg_name, _packages[0]['path'], _paths['params'], downloader, self, parser,
_params_tmp, _params_raw, _stat_pkg)
_mark = 'chosen'
self._log.info(' {}: {}'.format(_mark, str(_packages[0]['path'])))
elif len(_packages) > 1:
raise CrosspmException(
CROSSPM_ERRORCODE_MULTIPLE_DEPS,
'Multiple instances found for package [{}] not found.'.format(_pkg_name)
)
else:
# Package not found: may be error, but it could be in other source.
pass
else:
# Package not found: may be error, but it could be in other source.
pass
if (_package is not None) or (not self._config.no_fails):
_added, _package = downloader.add_package(_pkg_name, _package)
else:
_added = False
if _package is not None:
_pkg_name = _package.name
if _added or (_package is not None):
if (_package is not None) or (not self._config.no_fails):
if (_package is not None) or (_packages_found.get(_pkg_name, None) is None):
_packages_found[_pkg_name] = _package
if _added and (_package is not None):
if downloader.do_load:
_package.download()
_deps_file = _package.get_file(self._config.deps_lock_file_name)
if not _deps_file:
_deps_file = _package.get_file(CROSSPM_DEPENDENCY_LOCK_FILENAME)
if _deps_file:
_package.find_dependencies(_deps_file)
elif self._config.deps_file_name:
_deps_file = _package.get_file(self._config.deps_file_name)
if _deps_file and os.path.isfile(_deps_file):
_package.find_dependencies(_deps_file)
return _packages_found
@staticmethod
def pkg_stat(package):
_stat_attr = {'ctime': 'st_atime',
'mtime': 'st_mtime',
'size': 'st_size'}
_stat_pkg = os.stat(str(package))
_stat_pkg = {k: getattr(_stat_pkg, v, None) for k, v in _stat_attr.items()}
return _stat_pkg
def download_package(self, package, dest_path):
dest_dir = os.path.dirname(dest_path)
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
elif os.path.exists(dest_path):
os.remove(dest_path)
try:
_stat_pkg = self.pkg_stat(package)
shutil.copyfile(str(package), dest_path)
os.utime(dest_path, (_stat_pkg['ctime'], _stat_pkg['mtime']))
except Exception as e:
code = CROSSPM_ERRORCODE_SERVER_CONNECT_ERROR
msg = 'FAILED to download package {} at url: [{}]'.format(
package.name,
str(package),
)
raise CrosspmException(code, msg) from e
return dest_path
@staticmethod
def get_package_filename(package):
if isinstance(package, FilesPath):
return package.name
return ''
@staticmethod
def get_package_path(package):
if isinstance(package, FilesPath):
return str(package)
return ''
| mit | 0d066e3060c19e6db2253e3927d0f867 | 40.796992 | 115 | 0.475355 | 4.569667 | false | false | false | false |
mwouts/jupytext | jupytext/compare.py | 1 | 12936 | """Compare two Jupyter notebooks"""
import difflib
import json
import re
from .cell_metadata import _IGNORE_CELL_METADATA
from .combine import combine_inputs_with_outputs
from .formats import long_form_one_format
from .header import _DEFAULT_NOTEBOOK_METADATA
from .jupytext import reads, writes
from .metadata_filter import filter_metadata
_BLANK_LINE = re.compile(r"^\s*$")
def _multilines(obj):
try:
lines = obj.splitlines()
return lines + [""] if obj.endswith("\n") else lines
except AttributeError:
# Remove the final blank space on Python 2.7
# return json.dumps(obj, indent=True, sort_keys=True).splitlines()
return [
line.rstrip()
for line in json.dumps(obj, indent=True, sort_keys=True).splitlines()
]
def compare(
actual, expected, actual_name="actual", expected_name="expected", return_diff=False
):
"""Compare two strings, lists or dict-like objects"""
if actual != expected:
diff = difflib.unified_diff(
_multilines(expected),
_multilines(actual),
expected_name,
actual_name,
lineterm="",
)
if expected_name == "" and actual_name == "":
diff = list(diff)[2:]
diff = "\n".join(diff)
if return_diff:
return diff
raise AssertionError("\n" + diff)
return "" if return_diff else None
def filtered_cell(cell, preserve_outputs, cell_metadata_filter):
"""Cell type, metadata and source from given cell"""
filtered = {
"cell_type": cell.cell_type,
"source": cell.source,
"metadata": filter_metadata(
cell.metadata, cell_metadata_filter, _IGNORE_CELL_METADATA
),
}
if preserve_outputs:
for key in ["execution_count", "outputs"]:
if key in cell:
filtered[key] = cell[key]
return filtered
def filtered_notebook_metadata(notebook, ignore_display_name=False):
"""Notebook metadata, filtered for metadata added by Jupytext itself"""
metadata = filter_metadata(
notebook.metadata,
notebook.metadata.get("jupytext", {}).get("notebook_metadata_filter"),
_DEFAULT_NOTEBOOK_METADATA,
)
# The display name for the kernel might change (Quarto format on the CI)
if ignore_display_name:
metadata.get("kernelspec", {}).pop("display_name", None)
if "jupytext" in metadata:
del metadata["jupytext"]
return metadata
class NotebookDifference(Exception):
"""Report notebook differences"""
def same_content(ref_source, test_source, allow_removed_final_blank_line):
"""Is the content of two cells the same, except for an optional final blank line?"""
if ref_source == test_source:
return True
if not allow_removed_final_blank_line:
return False
# Is ref identical to test, plus one blank line?
ref_source = ref_source.splitlines()
test_source = test_source.splitlines()
if not ref_source:
return False
if ref_source[:-1] != test_source:
return False
return _BLANK_LINE.match(ref_source[-1])
def compare_notebooks(
notebook_actual,
notebook_expected,
fmt=None,
allow_expected_differences=True,
raise_on_first_difference=True,
compare_outputs=False,
compare_ids=None,
):
"""Compare the two notebooks, and raise with a meaningful message
that explains the differences, if any"""
fmt = long_form_one_format(fmt)
format_name = fmt.get("format_name")
if (
format_name == "sphinx"
and notebook_actual.cells
and notebook_actual.cells[0].source == "%matplotlib inline"
):
notebook_actual.cells = notebook_actual.cells[1:]
if compare_ids is None:
compare_ids = compare_outputs
modified_cells, modified_cell_metadata = compare_cells(
notebook_actual.cells,
notebook_expected.cells,
raise_on_first_difference,
compare_outputs=compare_outputs,
compare_ids=compare_ids,
cell_metadata_filter=notebook_actual.get("jupytext", {}).get(
"cell_metadata_filter"
),
allow_missing_code_cell_metadata=(
allow_expected_differences and format_name == "sphinx"
),
allow_missing_markdown_cell_metadata=(
allow_expected_differences and format_name in ["sphinx", "spin"]
),
allow_filtered_cell_metadata=allow_expected_differences,
allow_removed_final_blank_line=allow_expected_differences,
)
# Compare notebook metadata
modified_metadata = False
try:
ignore_display_name = (
fmt.get("extension") == ".qmd" and allow_expected_differences
)
compare(
filtered_notebook_metadata(notebook_actual, ignore_display_name),
filtered_notebook_metadata(notebook_expected, ignore_display_name),
)
except AssertionError as error:
if raise_on_first_difference:
raise NotebookDifference(f"Notebook metadata differ: {str(error)}")
modified_metadata = True
error = []
if modified_cells:
error.append(
"Cells {} differ ({}/{})".format(
",".join([str(i) for i in modified_cells]),
len(modified_cells),
len(notebook_expected.cells),
)
)
if modified_cell_metadata:
error.append(
"Cell metadata '{}' differ".format(
"', '".join([str(i) for i in modified_cell_metadata])
)
)
if modified_metadata:
error.append("Notebook metadata differ")
if error:
raise NotebookDifference(" | ".join(error))
def compare_cells(
actual_cells,
expected_cells,
raise_on_first_difference=True,
compare_outputs=True,
compare_ids=True,
cell_metadata_filter=None,
allow_missing_code_cell_metadata=False,
allow_missing_markdown_cell_metadata=False,
allow_filtered_cell_metadata=False,
allow_removed_final_blank_line=False,
):
"""Compare two collection of notebook cells"""
test_cell_iter = iter(actual_cells)
modified_cells = set()
modified_cell_metadata = set()
for i, ref_cell in enumerate(expected_cells, 1):
try:
test_cell = next(test_cell_iter)
except StopIteration:
if raise_on_first_difference:
raise NotebookDifference(
"No cell corresponding to {} cell #{}:\n{}".format(
ref_cell.cell_type, i, ref_cell.source
)
)
modified_cells.update(range(i, len(expected_cells) + 1))
break
ref_lines = [
line for line in ref_cell.source.splitlines() if not _BLANK_LINE.match(line)
]
test_lines = []
# 1. test cell type
if ref_cell.cell_type != test_cell.cell_type:
if raise_on_first_difference:
raise NotebookDifference(
"Unexpected cell type '{}' for {} cell #{}:\n{}".format(
test_cell.cell_type, ref_cell.cell_type, i, ref_cell.source
)
)
modified_cells.add(i)
# Compare cell ids (introduced in nbformat 5.1.0)
if compare_ids and test_cell.get("id") != ref_cell.get("id"):
if raise_on_first_difference:
raise NotebookDifference(
f"Cell ids differ on {test_cell['cell_type']} cell #{i}: "
f"'{test_cell.get('id')}' != '{ref_cell.get('id')}'"
)
modified_cells.add(i)
# 2. test cell metadata
if (ref_cell.cell_type == "code" and not allow_missing_code_cell_metadata) or (
ref_cell.cell_type != "code" and not allow_missing_markdown_cell_metadata
):
ref_metadata = ref_cell.metadata
test_metadata = test_cell.metadata
if allow_filtered_cell_metadata:
ref_metadata = {
key: ref_metadata[key]
for key in ref_metadata
if key not in _IGNORE_CELL_METADATA
}
test_metadata = {
key: test_metadata[key]
for key in test_metadata
if key not in _IGNORE_CELL_METADATA
}
if ref_metadata != test_metadata:
if raise_on_first_difference:
try:
compare(test_metadata, ref_metadata)
except AssertionError as error:
raise NotebookDifference(
"Metadata differ on {} cell #{}: {}\nCell content:\n{}".format(
test_cell.cell_type, i, str(error), ref_cell.source
)
)
else:
modified_cell_metadata.update(
set(test_metadata).difference(ref_metadata)
)
modified_cell_metadata.update(
set(ref_metadata).difference(test_metadata)
)
for key in set(ref_metadata).intersection(test_metadata):
if ref_metadata[key] != test_metadata[key]:
modified_cell_metadata.add(key)
test_lines.extend(
[
line
for line in test_cell.source.splitlines()
if not _BLANK_LINE.match(line)
]
)
# 3. test cell content
if ref_lines != test_lines:
if raise_on_first_difference:
try:
compare("\n".join(test_lines), "\n".join(ref_lines))
except AssertionError as error:
raise NotebookDifference(
"Cell content differ on {} cell #{}: {}".format(
test_cell.cell_type, i, str(error)
)
)
else:
modified_cells.add(i)
# 3. bis test entire cell content
if not same_content(
ref_cell.source, test_cell.source, allow_removed_final_blank_line
):
if ref_cell.source != test_cell.source:
if raise_on_first_difference:
diff = compare(test_cell.source, ref_cell.source, return_diff=True)
raise NotebookDifference(
"Cell content differ on {} cell #{}: {}".format(
test_cell.cell_type, i, diff
)
)
modified_cells.add(i)
if not compare_outputs:
continue
if ref_cell.cell_type != "code":
continue
ref_cell = filtered_cell(
ref_cell,
preserve_outputs=compare_outputs,
cell_metadata_filter=cell_metadata_filter,
)
test_cell = filtered_cell(
test_cell,
preserve_outputs=compare_outputs,
cell_metadata_filter=cell_metadata_filter,
)
try:
compare(test_cell, ref_cell)
except AssertionError as error:
if raise_on_first_difference:
raise NotebookDifference(
"Cell outputs differ on {} cell #{}: {}".format(
test_cell["cell_type"], i, str(error)
)
)
modified_cells.add(i)
# More cells in the actual notebook?
remaining_cell_count = 0
while True:
try:
test_cell = next(test_cell_iter)
if raise_on_first_difference:
raise NotebookDifference(
"Additional {} cell: {}".format(
test_cell.cell_type, test_cell.source
)
)
remaining_cell_count += 1
except StopIteration:
break
if remaining_cell_count and not raise_on_first_difference:
modified_cells.update(
range(
len(expected_cells) + 1,
len(expected_cells) + 1 + remaining_cell_count,
)
)
return modified_cells, modified_cell_metadata
def test_round_trip_conversion(
notebook, fmt, update, allow_expected_differences=True, stop_on_first_error=True
):
"""Test round trip conversion for a Jupyter notebook"""
text = writes(notebook, fmt)
round_trip = reads(text, fmt)
if update:
round_trip = combine_inputs_with_outputs(round_trip, notebook, fmt)
compare_notebooks(
round_trip,
notebook,
fmt,
allow_expected_differences,
raise_on_first_difference=stop_on_first_error,
)
| mit | ab9f3b799878b4f0aa46153a8562a598 | 32.084399 | 91 | 0.551716 | 4.312 | false | true | false | false |
mwouts/jupytext | tests/test_read_incomplete_rmd.py | 1 | 1798 | import jupytext
def test_incomplete_header(
rmd="""---
title: Incomplete header
```{python}
1+1
```
""",
):
nb = jupytext.reads(rmd, "Rmd")
assert len(nb.cells) == 2
assert nb.cells[0].cell_type == "markdown"
assert nb.cells[0].source == "---\ntitle: Incomplete header"
assert nb.cells[1].cell_type == "code"
assert nb.cells[1].source == "1+1"
def test_code_in_markdown_block(
rmd="""```{python}
a = 1
b = 2
a + b
```
```python
'''Code here goes to a Markdown cell'''
'''even if we have two blank lines above'''
```
```{bash}
ls -l
```
""",
):
nb = jupytext.reads(rmd, "Rmd")
assert len(nb.cells) == 3
assert nb.cells[0].cell_type == "code"
assert nb.cells[0].source == "a = 1\nb = 2\na + b"
assert nb.cells[1].cell_type == "markdown"
assert (
nb.cells[1].source
== """```python
'''Code here goes to a Markdown cell'''
'''even if we have two blank lines above'''
```"""
)
assert nb.cells[2].cell_type == "code"
assert nb.cells[2].source == "%%bash\nls -l"
def test_unterminated_header(
rmd="""---
title: Unterminated header
```{python}
1+3
```
some text
```{r}
1+4
```
```{python not_terminated}
1+5
""",
):
nb = jupytext.reads(rmd, "Rmd")
assert len(nb.cells) == 5
assert nb.cells[0].cell_type == "markdown"
assert nb.cells[0].source == "---\ntitle: Unterminated header"
assert nb.cells[1].cell_type == "code"
assert nb.cells[1].source == "1+3"
assert nb.cells[2].cell_type == "markdown"
assert nb.cells[2].source == "some text"
assert nb.cells[3].cell_type == "code"
assert nb.cells[3].source == "%%R\n1+4"
assert nb.cells[4].cell_type == "code"
assert nb.cells[4].metadata == {"name": "not_terminated"}
assert nb.cells[4].source == "1+5"
| mit | 42056b95e7048ea65e0da28871f5dd65 | 19.431818 | 66 | 0.580089 | 2.840442 | false | false | false | false |
pureqml/qmlcore | platform/android/build.py | 1 | 1685 | #!/usr/bin/env python
from __future__ import print_function
import argparse
import os
def build(app, title, release):
os.system('rm -rf %s' %app)
res = os.system('cordova create %s com.%s.app %s' %(app, app, title))
if res != 0:
print("Failed to create android app")
return
os.system('rsync -a ./ %s/www --exclude=%s ' %(app,app))
os.system('cp androidIcon.png %s' %(app))
os.system('cp config.xml %s' %(app))
os.chdir(app)
os.system('cordova platform add android')
{% block commands %}{% endblock %}
os.system('cordova plugin add cordova-plugin-streaming-media')
os.system('cordova plugin add cordova-plugin-device')
os.system('cordova plugin add cordova-plugin-screen-orientation')
{% block plugins %}{% endblock %}
if release:
{% if androidBuild %}
build = 'cordova build android --release -- '
os.system(build + '--keystore={{androidBuild.keystore}} --storePassword={{androidBuild.storePassword}} --alias={{androidBuild.alias}} --password={{androidBuild.password}}')
{% else %}
print("Failed to build release apk androidBuild property is undefined")
{% endif %}
else:
os.system('cordova build android')
os.chdir('..')
parser = argparse.ArgumentParser('pureqml cordova android build tool')
parser.add_argument('--app', '-a', help='application name', default="app")
parser.add_argument('--title', '-t', help='application title', default="App")
parser.add_argument('--release', '-r', help='build release apk', default=False)
args = parser.parse_args()
res = os.system('cordova --version')
if res == 0:
build(args.app, args.title, args.release)
else:
print('Install "cordova" first: https://cordova.apache.org/docs/en/latest/guide/cli/')
| mit | 86215ad42a77543b3c9ea6f46c79ca5e | 32.039216 | 174 | 0.689614 | 3.12037 | false | false | false | false |
twilio/twilio-python | tests/integration/supersim/v1/test_usage_record.py | 1 | 29251 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class UsageRecordTestCase(IntegrationTestCase):
def test_list_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.supersim.v1.usage_records.list()
self.holodeck.assert_has_request(Request(
'get',
'https://supersim.twilio.com/v1/UsageRecords',
))
def test_read_all_response(self):
self.holodeck.mock(Response(
200,
'''
{
"usage_records": [
{
"period": {
"start_time": "2015-05-01T20:00:00Z",
"end_time": "2015-06-01T20:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": null,
"fleet_sid": null,
"network_sid": null,
"iso_country": null
}
],
"meta": {
"first_page_url": "https://supersim.twilio.com/v1/UsageRecords?PageSize=50&Page=0",
"key": "usage_records",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
"url": "https://supersim.twilio.com/v1/UsageRecords?PageSize=50&Page=0"
}
}
'''
))
actual = self.client.supersim.v1.usage_records.list()
self.assertIsNotNone(actual)
def test_read_all_day_response(self):
self.holodeck.mock(Response(
200,
'''
{
"usage_records": [
{
"period": {
"start_time": "2019-05-03T00:00:00Z",
"end_time": "2019-05-04T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": null,
"fleet_sid": null,
"network_sid": null,
"iso_country": null
},
{
"period": {
"start_time": "2019-05-02T00:00:00Z",
"end_time": "2019-05-03T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": null,
"fleet_sid": null,
"network_sid": null,
"iso_country": null
}
],
"meta": {
"first_page_url": "https://supersim.twilio.com/v1/UsageRecords?Granularity=day&PageSize=50&Page=0",
"key": "usage_records",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
"url": "https://supersim.twilio.com/v1/UsageRecords?Granularity=day&PageSize=50&Page=0"
}
}
'''
))
actual = self.client.supersim.v1.usage_records.list()
self.assertIsNotNone(actual)
def test_read_all_hour_response(self):
self.holodeck.mock(Response(
200,
'''
{
"usage_records": [
{
"period": {
"start_time": "2019-05-01T01:00:00Z",
"end_time": "2019-05-01T02:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": null,
"fleet_sid": null,
"network_sid": null,
"iso_country": null
},
{
"period": {
"start_time": "2019-05-01T00:00:00Z",
"end_time": "2019-05-01T01:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": null,
"fleet_sid": null,
"network_sid": null,
"iso_country": null
}
],
"meta": {
"first_page_url": "https://supersim.twilio.com/v1/UsageRecords?Granularity=hour&PageSize=50&Page=0",
"key": "usage_records",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
"url": "https://supersim.twilio.com/v1/UsageRecords?Granularity=hour&PageSize=50&Page=0"
}
}
'''
))
actual = self.client.supersim.v1.usage_records.list()
self.assertIsNotNone(actual)
def test_read_day_sim_filter_response(self):
self.holodeck.mock(Response(
200,
'''
{
"usage_records": [
{
"period": {
"start_time": "2019-05-03T00:00:00Z",
"end_time": "2019-05-04T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"sim_sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"fleet_sid": null,
"network_sid": null,
"iso_country": null
},
{
"period": {
"start_time": "2019-05-02T00:00:00Z",
"end_time": "2019-05-03T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"fleet_sid": null,
"network_sid": null,
"iso_country": null
}
],
"meta": {
"first_page_url": "https://supersim.twilio.com/v1/UsageRecords?Sim=HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Granularity=day&PageSize=50&Page=0",
"key": "usage_records",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
"url": "https://supersim.twilio.com/v1/UsageRecords?Sim=HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Granularity=day&PageSize=50&Page=0"
}
}
'''
))
actual = self.client.supersim.v1.usage_records.list()
self.assertIsNotNone(actual)
def test_read_day_network_filter_response(self):
self.holodeck.mock(Response(
200,
'''
{
"usage_records": [
{
"period": {
"start_time": "2019-05-03T00:00:00Z",
"end_time": "2019-05-04T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": null,
"fleet_sid": null,
"network_sid": "HWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"iso_country": null
},
{
"period": {
"start_time": "2019-05-02T00:00:00Z",
"end_time": "2019-05-03T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": null,
"fleet_sid": null,
"network_sid": "HWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"iso_country": null
}
],
"meta": {
"first_page_url": "https://supersim.twilio.com/v1/UsageRecords?Network=HWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Granularity=day&PageSize=50&Page=0",
"key": "usage_records",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
"url": "https://supersim.twilio.com/v1/UsageRecords?Network=HWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Granularity=day&PageSize=50&Page=0"
}
}
'''
))
actual = self.client.supersim.v1.usage_records.list()
self.assertIsNotNone(actual)
def test_read_day_country_filter_response(self):
self.holodeck.mock(Response(
200,
'''
{
"usage_records": [
{
"period": {
"start_time": "2019-05-03T00:00:00Z",
"end_time": "2019-05-04T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": null,
"fleet_sid": null,
"network_sid": null,
"iso_country": "FR"
},
{
"period": {
"start_time": "2019-05-02T00:00:00Z",
"end_time": "2019-05-03T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": null,
"fleet_sid": null,
"network_sid": null,
"iso_country": "FR"
}
],
"meta": {
"first_page_url": "https://supersim.twilio.com/v1/UsageRecords?IsoCountry=FR&Granularity=day&PageSize=50&Page=0",
"key": "usage_records",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
"url": "https://supersim.twilio.com/v1/UsageRecords?IsoCountry=FR&Granularity=day&PageSize=50&Page=0"
}
}
'''
))
actual = self.client.supersim.v1.usage_records.list()
self.assertIsNotNone(actual)
def test_read_day_fleet_filter_response(self):
self.holodeck.mock(Response(
200,
'''
{
"usage_records": [
{
"period": {
"start_time": "2019-05-03T00:00:00Z",
"end_time": "2019-05-04T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": null,
"fleet_sid": "HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"network_sid": null,
"iso_country": null
},
{
"period": {
"start_time": "2019-05-02T00:00:00Z",
"end_time": "2019-05-03T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": null,
"fleet_sid": "HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"network_sid": null,
"iso_country": null
}
],
"meta": {
"first_page_url": "https://supersim.twilio.com/v1/UsageRecords?Fleet=HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Granularity=day&PageSize=50&Page=0",
"key": "usage_records",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
"url": "https://supersim.twilio.com/v1/UsageRecords?Fleet=HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Granularity=day&PageSize=50&Page=0"
}
}
'''
))
actual = self.client.supersim.v1.usage_records.list()
self.assertIsNotNone(actual)
def test_read_day_group_by_sim_response(self):
self.holodeck.mock(Response(
200,
'''
{
"usage_records": [
{
"period": {
"start_time": "2019-05-03T00:00:00Z",
"end_time": "2019-05-04T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"fleet_sid": null,
"network_sid": null,
"iso_country": null
},
{
"period": {
"start_time": "2019-05-03T00:00:00Z",
"end_time": "2019-05-04T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": "HSbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"fleet_sid": null,
"network_sid": null,
"iso_country": null
}
],
"meta": {
"first_page_url": "https://supersim.twilio.com/v1/UsageRecords?Group=sim&PageSize=50&Page=0",
"key": "usage_records",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
"url": "https://supersim.twilio.com/v1/UsageRecords?Group=sim&PageSize=50&Page=0"
}
}
'''
))
actual = self.client.supersim.v1.usage_records.list()
self.assertIsNotNone(actual)
def test_read_day_group_by_fleet_response(self):
self.holodeck.mock(Response(
200,
'''
{
"usage_records": [
{
"period": {
"start_time": "2019-05-03T00:00:00Z",
"end_time": "2019-05-04T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": null,
"fleet_sid": "HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"network_sid": null,
"iso_country": null
},
{
"period": {
"start_time": "2019-05-03T00:00:00Z",
"end_time": "2019-05-04T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": null,
"fleet_sid": "HFbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"network_sid": null,
"iso_country": null
}
],
"meta": {
"first_page_url": "https://supersim.twilio.com/v1/UsageRecords?Group=fleet&PageSize=50&Page=0",
"key": "usage_records",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
"url": "https://supersim.twilio.com/v1/UsageRecords?Group=fleet&PageSize=50&Page=0"
}
}
'''
))
actual = self.client.supersim.v1.usage_records.list()
self.assertIsNotNone(actual)
def test_read_day_group_by_network_response(self):
self.holodeck.mock(Response(
200,
'''
{
"usage_records": [
{
"period": {
"start_time": "2019-05-03T00:00:00Z",
"end_time": "2019-05-04T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": null,
"fleet_sid": null,
"network_sid": "HWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"iso_country": null
},
{
"period": {
"start_time": "2019-05-03T00:00:00Z",
"end_time": "2019-05-04T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": null,
"fleet_sid": null,
"network_sid": "HWbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"iso_country": null
}
],
"meta": {
"first_page_url": "https://supersim.twilio.com/v1/UsageRecords?Group=network&PageSize=50&Page=0",
"key": "usage_records",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
"url": "https://supersim.twilio.com/v1/UsageRecords?Group=network&PageSize=50&Page=0"
}
}
'''
))
actual = self.client.supersim.v1.usage_records.list()
self.assertIsNotNone(actual)
def test_read_day_group_by_iso_country_response(self):
self.holodeck.mock(Response(
200,
'''
{
"usage_records": [
{
"period": {
"start_time": "2019-05-03T00:00:00Z",
"end_time": "2019-05-04T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": null,
"fleet_sid": null,
"network_sid": null,
"iso_country": "FR"
},
{
"period": {
"start_time": "2019-05-03T00:00:00Z",
"end_time": "2019-05-04T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": null,
"fleet_sid": null,
"network_sid": null,
"iso_country": "US"
}
],
"meta": {
"first_page_url": "https://supersim.twilio.com/v1/UsageRecords?Group=isoCountry&PageSize=50&Page=0",
"key": "usage_records",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
"url": "https://supersim.twilio.com/v1/UsageRecords?Group=isoCountry&PageSize=50&Page=0"
}
}
'''
))
actual = self.client.supersim.v1.usage_records.list()
self.assertIsNotNone(actual)
def test_read_day_group_by_sim_and_filter_by_country_response(self):
self.holodeck.mock(Response(
200,
'''
{
"usage_records": [
{
"period": {
"start_time": "2019-05-03T00:00:00Z",
"end_time": "2019-05-04T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"fleet_sid": null,
"network_sid": null,
"iso_country": "FR"
},
{
"period": {
"start_time": "2019-05-03T00:00:00Z",
"end_time": "2019-05-04T00:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 150000,
"data_download": 150000,
"data_total": 300000,
"data_total_billed": "0.03",
"billed_unit": "USD",
"sim_sid": "HSbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"fleet_sid": null,
"network_sid": null,
"iso_country": "FR"
}
],
"meta": {
"first_page_url": "https://supersim.twilio.com/v1/UsageRecords?IsoCountry=FR&Group=sim&PageSize=50&Page=0",
"key": "usage_records",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
"url": "https://supersim.twilio.com/v1/UsageRecords?IsoCountry=FR&Group=sim&PageSize=50&Page=0"
}
}
'''
))
actual = self.client.supersim.v1.usage_records.list()
self.assertIsNotNone(actual)
def test_read_all_no_billing_response(self):
self.holodeck.mock(Response(
200,
'''
{
"usage_records": [
{
"period": {
"start_time": "2015-05-01T20:00:00Z",
"end_time": "2015-06-01T20:00:00Z"
},
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"data_upload": 1000,
"data_download": 1000,
"data_total": 2000,
"data_total_billed": "0",
"billed_unit": null,
"sim_sid": null,
"fleet_sid": null,
"network_sid": null,
"iso_country": null
}
],
"meta": {
"first_page_url": "https://supersim.twilio.com/v1/UsageRecords?PageSize=50&Page=0",
"key": "usage_records",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
"url": "https://supersim.twilio.com/v1/UsageRecords?PageSize=50&Page=0"
}
}
'''
))
actual = self.client.supersim.v1.usage_records.list()
self.assertIsNotNone(actual)
| mit | 6975984b3243e58720f77a3801509c05 | 39.51385 | 162 | 0.379953 | 4.556231 | false | false | false | false |
twilio/twilio-python | twilio/rest/studio/v1/flow/engagement/__init__.py | 1 | 16213 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
from twilio.rest.studio.v1.flow.engagement.engagement_context import EngagementContextList
from twilio.rest.studio.v1.flow.engagement.step import StepList
class EngagementList(ListResource):
def __init__(self, version, flow_sid):
"""
Initialize the EngagementList
:param Version version: Version that contains the resource
:param flow_sid: The SID of the Flow
:returns: twilio.rest.studio.v1.flow.engagement.EngagementList
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementList
"""
super(EngagementList, self).__init__(version)
# Path Solution
self._solution = {'flow_sid': flow_sid, }
self._uri = '/Flows/{flow_sid}/Engagements'.format(**self._solution)
def stream(self, limit=None, page_size=None):
"""
Streams EngagementInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.studio.v1.flow.engagement.EngagementInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, limit=None, page_size=None):
"""
Lists EngagementInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.studio.v1.flow.engagement.EngagementInstance]
"""
return list(self.stream(limit=limit, page_size=page_size, ))
def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of EngagementInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of EngagementInstance
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementPage
"""
data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })
response = self._version.page(method='GET', uri=self._uri, params=data, )
return EngagementPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of EngagementInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of EngagementInstance
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return EngagementPage(self._version, response, self._solution)
def create(self, to, from_, parameters=values.unset):
"""
Create the EngagementInstance
:param unicode to: The Contact phone number to start a Studio Flow Engagement
:param unicode from_: The Twilio phone number to send messages or initiate calls from during the Flow Engagement
:param dict parameters: A JSON string we will add to your flow's context and that you can access as variables inside your flow
:returns: The created EngagementInstance
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance
"""
data = values.of({'To': to, 'From': from_, 'Parameters': serialize.object(parameters), })
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return EngagementInstance(self._version, payload, flow_sid=self._solution['flow_sid'], )
def get(self, sid):
"""
Constructs a EngagementContext
:param sid: The SID of the Engagement resource to fetch
:returns: twilio.rest.studio.v1.flow.engagement.EngagementContext
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementContext
"""
return EngagementContext(self._version, flow_sid=self._solution['flow_sid'], sid=sid, )
def __call__(self, sid):
"""
Constructs a EngagementContext
:param sid: The SID of the Engagement resource to fetch
:returns: twilio.rest.studio.v1.flow.engagement.EngagementContext
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementContext
"""
return EngagementContext(self._version, flow_sid=self._solution['flow_sid'], sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Studio.V1.EngagementList>'
class EngagementPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the EngagementPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param flow_sid: The SID of the Flow
:returns: twilio.rest.studio.v1.flow.engagement.EngagementPage
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementPage
"""
super(EngagementPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of EngagementInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.studio.v1.flow.engagement.EngagementInstance
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance
"""
return EngagementInstance(self._version, payload, flow_sid=self._solution['flow_sid'], )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Studio.V1.EngagementPage>'
class EngagementContext(InstanceContext):
def __init__(self, version, flow_sid, sid):
"""
Initialize the EngagementContext
:param Version version: Version that contains the resource
:param flow_sid: Flow SID
:param sid: The SID of the Engagement resource to fetch
:returns: twilio.rest.studio.v1.flow.engagement.EngagementContext
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementContext
"""
super(EngagementContext, self).__init__(version)
# Path Solution
self._solution = {'flow_sid': flow_sid, 'sid': sid, }
self._uri = '/Flows/{flow_sid}/Engagements/{sid}'.format(**self._solution)
# Dependents
self._steps = None
self._engagement_context = None
def fetch(self):
"""
Fetch the EngagementInstance
:returns: The fetched EngagementInstance
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return EngagementInstance(
self._version,
payload,
flow_sid=self._solution['flow_sid'],
sid=self._solution['sid'],
)
def delete(self):
"""
Deletes the EngagementInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
@property
def steps(self):
"""
Access the steps
:returns: twilio.rest.studio.v1.flow.engagement.step.StepList
:rtype: twilio.rest.studio.v1.flow.engagement.step.StepList
"""
if self._steps is None:
self._steps = StepList(
self._version,
flow_sid=self._solution['flow_sid'],
engagement_sid=self._solution['sid'],
)
return self._steps
@property
def engagement_context(self):
"""
Access the engagement_context
:returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList
:rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList
"""
if self._engagement_context is None:
self._engagement_context = EngagementContextList(
self._version,
flow_sid=self._solution['flow_sid'],
engagement_sid=self._solution['sid'],
)
return self._engagement_context
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Studio.V1.EngagementContext {}>'.format(context)
class EngagementInstance(InstanceResource):
class Status(object):
ACTIVE = "active"
ENDED = "ended"
def __init__(self, version, payload, flow_sid, sid=None):
"""
Initialize the EngagementInstance
:returns: twilio.rest.studio.v1.flow.engagement.EngagementInstance
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance
"""
super(EngagementInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'account_sid': payload.get('account_sid'),
'flow_sid': payload.get('flow_sid'),
'contact_sid': payload.get('contact_sid'),
'contact_channel_address': payload.get('contact_channel_address'),
'context': payload.get('context'),
'status': payload.get('status'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'url': payload.get('url'),
'links': payload.get('links'),
}
# Context
self._context = None
self._solution = {'flow_sid': flow_sid, 'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: EngagementContext for this EngagementInstance
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementContext
"""
if self._context is None:
self._context = EngagementContext(
self._version,
flow_sid=self._solution['flow_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def flow_sid(self):
"""
:returns: The SID of the Flow
:rtype: unicode
"""
return self._properties['flow_sid']
@property
def contact_sid(self):
"""
:returns: The SID of the Contact
:rtype: unicode
"""
return self._properties['contact_sid']
@property
def contact_channel_address(self):
"""
:returns: The phone number, SIP address or Client identifier that triggered this Engagement
:rtype: unicode
"""
return self._properties['contact_channel_address']
@property
def context(self):
"""
:returns: The current state of the execution flow
:rtype: dict
"""
return self._properties['context']
@property
def status(self):
"""
:returns: The status of the Engagement
:rtype: EngagementInstance.Status
"""
return self._properties['status']
@property
def date_created(self):
"""
:returns: The ISO 8601 date and time in GMT when the Engagement was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The ISO 8601 date and time in GMT when the Engagement was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def url(self):
"""
:returns: The absolute URL of the resource
:rtype: unicode
"""
return self._properties['url']
@property
def links(self):
"""
:returns: The URLs of the Engagement's nested resources
:rtype: unicode
"""
return self._properties['links']
def fetch(self):
"""
Fetch the EngagementInstance
:returns: The fetched EngagementInstance
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance
"""
return self._proxy.fetch()
def delete(self):
"""
Deletes the EngagementInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
@property
def steps(self):
"""
Access the steps
:returns: twilio.rest.studio.v1.flow.engagement.step.StepList
:rtype: twilio.rest.studio.v1.flow.engagement.step.StepList
"""
return self._proxy.steps
@property
def engagement_context(self):
"""
Access the engagement_context
:returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList
:rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList
"""
return self._proxy.engagement_context
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Studio.V1.EngagementInstance {}>'.format(context)
| mit | f3cd2660569f64431546f7f6aad380dd | 32.847599 | 134 | 0.614569 | 4.273326 | false | false | false | false |
twilio/twilio-python | twilio/rest/numbers/v2/regulatory_compliance/end_user.py | 1 | 14458 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class EndUserList(ListResource):
def __init__(self, version):
"""
Initialize the EndUserList
:param Version version: Version that contains the resource
:returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserList
:rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserList
"""
super(EndUserList, self).__init__(version)
# Path Solution
self._solution = {}
self._uri = '/RegulatoryCompliance/EndUsers'.format(**self._solution)
def create(self, friendly_name, type, attributes=values.unset):
"""
Create the EndUserInstance
:param unicode friendly_name: The string that you assigned to describe the resource
:param EndUserInstance.Type type: The type of end user of the Bundle resource
:param dict attributes: The set of parameters that compose the End User resource
:returns: The created EndUserInstance
:rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance
"""
data = values.of({
'FriendlyName': friendly_name,
'Type': type,
'Attributes': serialize.object(attributes),
})
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return EndUserInstance(self._version, payload, )
def stream(self, limit=None, page_size=None):
"""
Streams EndUserInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, limit=None, page_size=None):
"""
Lists EndUserInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance]
"""
return list(self.stream(limit=limit, page_size=page_size, ))
def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of EndUserInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of EndUserInstance
:rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserPage
"""
data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })
response = self._version.page(method='GET', uri=self._uri, params=data, )
return EndUserPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of EndUserInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of EndUserInstance
:rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return EndUserPage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a EndUserContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext
:rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext
"""
return EndUserContext(self._version, sid=sid, )
def __call__(self, sid):
"""
Constructs a EndUserContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext
:rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext
"""
return EndUserContext(self._version, sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Numbers.V2.EndUserList>'
class EndUserPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the EndUserPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserPage
:rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserPage
"""
super(EndUserPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of EndUserInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance
:rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance
"""
return EndUserInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Numbers.V2.EndUserPage>'
class EndUserContext(InstanceContext):
def __init__(self, version, sid):
"""
Initialize the EndUserContext
:param Version version: Version that contains the resource
:param sid: The unique string that identifies the resource
:returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext
:rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext
"""
super(EndUserContext, self).__init__(version)
# Path Solution
self._solution = {'sid': sid, }
self._uri = '/RegulatoryCompliance/EndUsers/{sid}'.format(**self._solution)
def fetch(self):
"""
Fetch the EndUserInstance
:returns: The fetched EndUserInstance
:rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return EndUserInstance(self._version, payload, sid=self._solution['sid'], )
def update(self, friendly_name=values.unset, attributes=values.unset):
"""
Update the EndUserInstance
:param unicode friendly_name: The string that you assigned to describe the resource
:param dict attributes: The set of parameters that compose the End User resource
:returns: The updated EndUserInstance
:rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance
"""
data = values.of({'FriendlyName': friendly_name, 'Attributes': serialize.object(attributes), })
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return EndUserInstance(self._version, payload, sid=self._solution['sid'], )
def delete(self):
"""
Deletes the EndUserInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Numbers.V2.EndUserContext {}>'.format(context)
class EndUserInstance(InstanceResource):
class Type(object):
INDIVIDUAL = "individual"
BUSINESS = "business"
def __init__(self, version, payload, sid=None):
"""
Initialize the EndUserInstance
:returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance
:rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance
"""
super(EndUserInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'account_sid': payload.get('account_sid'),
'friendly_name': payload.get('friendly_name'),
'type': payload.get('type'),
'attributes': payload.get('attributes'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: EndUserContext for this EndUserInstance
:rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext
"""
if self._context is None:
self._context = EndUserContext(self._version, sid=self._solution['sid'], )
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def friendly_name(self):
"""
:returns: The string that you assigned to describe the resource
:rtype: unicode
"""
return self._properties['friendly_name']
@property
def type(self):
"""
:returns: The type of end user of the Bundle resource
:rtype: EndUserInstance.Type
"""
return self._properties['type']
@property
def attributes(self):
"""
:returns: The set of parameters that compose the End Users resource
:rtype: dict
"""
return self._properties['attributes']
@property
def date_created(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def url(self):
"""
:returns: The absolute URL of the End User resource
:rtype: unicode
"""
return self._properties['url']
def fetch(self):
"""
Fetch the EndUserInstance
:returns: The fetched EndUserInstance
:rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance
"""
return self._proxy.fetch()
def update(self, friendly_name=values.unset, attributes=values.unset):
"""
Update the EndUserInstance
:param unicode friendly_name: The string that you assigned to describe the resource
:param dict attributes: The set of parameters that compose the End User resource
:returns: The updated EndUserInstance
:rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance
"""
return self._proxy.update(friendly_name=friendly_name, attributes=attributes, )
def delete(self):
"""
Deletes the EndUserInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Numbers.V2.EndUserInstance {}>'.format(context)
| mit | 997462dc403da034c784bf9202b34d4b | 33.922705 | 103 | 0.628441 | 4.25987 | false | false | false | false |
twilio/twilio-python | twilio/rest/preview/trusted_comms/__init__.py | 1 | 2274 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base.version import Version
from twilio.rest.preview.trusted_comms.branded_channel import BrandedChannelList
from twilio.rest.preview.trusted_comms.brands_information import BrandsInformationList
from twilio.rest.preview.trusted_comms.cps import CpsList
from twilio.rest.preview.trusted_comms.current_call import CurrentCallList
class TrustedComms(Version):
def __init__(self, domain):
"""
Initialize the TrustedComms version of Preview
:returns: TrustedComms version of Preview
:rtype: twilio.rest.preview.trusted_comms.TrustedComms.TrustedComms
"""
super(TrustedComms, self).__init__(domain)
self.version = 'TrustedComms'
self._branded_channels = None
self._brands_information = None
self._cps = None
self._current_calls = None
@property
def branded_channels(self):
"""
:rtype: twilio.rest.preview.trusted_comms.branded_channel.BrandedChannelList
"""
if self._branded_channels is None:
self._branded_channels = BrandedChannelList(self)
return self._branded_channels
@property
def brands_information(self):
"""
:rtype: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationList
"""
if self._brands_information is None:
self._brands_information = BrandsInformationList(self)
return self._brands_information
@property
def cps(self):
"""
:rtype: twilio.rest.preview.trusted_comms.cps.CpsList
"""
if self._cps is None:
self._cps = CpsList(self)
return self._cps
@property
def current_calls(self):
"""
:rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallList
"""
if self._current_calls is None:
self._current_calls = CurrentCallList(self)
return self._current_calls
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Preview.TrustedComms>'
| mit | f2433f6bb444e237907257e505272ded | 29.32 | 90 | 0.627968 | 3.679612 | false | false | false | false |
twilio/twilio-python | twilio/rest/chat/v3/channel.py | 1 | 11327 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class ChannelList(ListResource):
def __init__(self, version):
"""
Initialize the ChannelList
:param Version version: Version that contains the resource
:returns: twilio.rest.chat.v3.channel.ChannelList
:rtype: twilio.rest.chat.v3.channel.ChannelList
"""
super(ChannelList, self).__init__(version)
# Path Solution
self._solution = {}
def get(self, service_sid, sid):
"""
Constructs a ChannelContext
:param service_sid: Service Sid.
:param sid: A string that uniquely identifies this Channel.
:returns: twilio.rest.chat.v3.channel.ChannelContext
:rtype: twilio.rest.chat.v3.channel.ChannelContext
"""
return ChannelContext(self._version, service_sid=service_sid, sid=sid, )
def __call__(self, service_sid, sid):
"""
Constructs a ChannelContext
:param service_sid: Service Sid.
:param sid: A string that uniquely identifies this Channel.
:returns: twilio.rest.chat.v3.channel.ChannelContext
:rtype: twilio.rest.chat.v3.channel.ChannelContext
"""
return ChannelContext(self._version, service_sid=service_sid, sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Chat.V3.ChannelList>'
class ChannelPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the ChannelPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.chat.v3.channel.ChannelPage
:rtype: twilio.rest.chat.v3.channel.ChannelPage
"""
super(ChannelPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of ChannelInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.chat.v3.channel.ChannelInstance
:rtype: twilio.rest.chat.v3.channel.ChannelInstance
"""
return ChannelInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Chat.V3.ChannelPage>'
class ChannelContext(InstanceContext):
def __init__(self, version, service_sid, sid):
"""
Initialize the ChannelContext
:param Version version: Version that contains the resource
:param service_sid: Service Sid.
:param sid: A string that uniquely identifies this Channel.
:returns: twilio.rest.chat.v3.channel.ChannelContext
:rtype: twilio.rest.chat.v3.channel.ChannelContext
"""
super(ChannelContext, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, 'sid': sid, }
self._uri = '/Services/{service_sid}/Channels/{sid}'.format(**self._solution)
def update(self, type=values.unset, messaging_service_sid=values.unset,
x_twilio_webhook_enabled=values.unset):
"""
Update the ChannelInstance
:param ChannelInstance.ChannelType type: The Type for this Channel to migrate to.
:param unicode messaging_service_sid: The unique ID of the Messaging Service this channel belongs to.
:param ChannelInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header
:returns: The updated ChannelInstance
:rtype: twilio.rest.chat.v3.channel.ChannelInstance
"""
data = values.of({'Type': type, 'MessagingServiceSid': messaging_service_sid, })
headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, })
payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, )
return ChannelInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
sid=self._solution['sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Chat.V3.ChannelContext {}>'.format(context)
class ChannelInstance(InstanceResource):
class ChannelType(object):
PUBLIC = "public"
PRIVATE = "private"
class WebhookEnabledType(object):
TRUE = "true"
FALSE = "false"
def __init__(self, version, payload, service_sid=None, sid=None):
"""
Initialize the ChannelInstance
:returns: twilio.rest.chat.v3.channel.ChannelInstance
:rtype: twilio.rest.chat.v3.channel.ChannelInstance
"""
super(ChannelInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'account_sid': payload.get('account_sid'),
'service_sid': payload.get('service_sid'),
'friendly_name': payload.get('friendly_name'),
'unique_name': payload.get('unique_name'),
'attributes': payload.get('attributes'),
'type': payload.get('type'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'created_by': payload.get('created_by'),
'members_count': deserialize.integer(payload.get('members_count')),
'messages_count': deserialize.integer(payload.get('messages_count')),
'messaging_service_sid': payload.get('messaging_service_sid'),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {
'service_sid': service_sid or self._properties['service_sid'],
'sid': sid or self._properties['sid'],
}
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ChannelContext for this ChannelInstance
:rtype: twilio.rest.chat.v3.channel.ChannelContext
"""
if self._context is None:
self._context = ChannelContext(
self._version,
service_sid=self._solution['service_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def service_sid(self):
"""
:returns: The SID of the Service that the resource is associated with
:rtype: unicode
"""
return self._properties['service_sid']
@property
def friendly_name(self):
"""
:returns: The string that you assigned to describe the resource
:rtype: unicode
"""
return self._properties['friendly_name']
@property
def unique_name(self):
"""
:returns: An application-defined string that uniquely identifies the resource
:rtype: unicode
"""
return self._properties['unique_name']
@property
def attributes(self):
"""
:returns: The JSON string that stores application-specific data
:rtype: unicode
"""
return self._properties['attributes']
@property
def type(self):
"""
:returns: The visibility of the channel. Can be: `public` or `private`
:rtype: ChannelInstance.ChannelType
"""
return self._properties['type']
@property
def date_created(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def created_by(self):
"""
:returns: The identity of the User that created the channel
:rtype: unicode
"""
return self._properties['created_by']
@property
def members_count(self):
"""
:returns: The number of Members in the Channel
:rtype: unicode
"""
return self._properties['members_count']
@property
def messages_count(self):
"""
:returns: The number of Messages that have been passed in the Channel
:rtype: unicode
"""
return self._properties['messages_count']
@property
def messaging_service_sid(self):
"""
:returns: The unique ID of the Messaging Service this channel belongs to.
:rtype: unicode
"""
return self._properties['messaging_service_sid']
@property
def url(self):
"""
:returns: The absolute URL of the Channel resource
:rtype: unicode
"""
return self._properties['url']
def update(self, type=values.unset, messaging_service_sid=values.unset,
x_twilio_webhook_enabled=values.unset):
"""
Update the ChannelInstance
:param ChannelInstance.ChannelType type: The Type for this Channel to migrate to.
:param unicode messaging_service_sid: The unique ID of the Messaging Service this channel belongs to.
:param ChannelInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header
:returns: The updated ChannelInstance
:rtype: twilio.rest.chat.v3.channel.ChannelInstance
"""
return self._proxy.update(
type=type,
messaging_service_sid=messaging_service_sid,
x_twilio_webhook_enabled=x_twilio_webhook_enabled,
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Chat.V3.ChannelInstance {}>'.format(context)
| mit | 5f899bb0bd79a00a8bcb66b20533f1de | 30.639665 | 124 | 0.606427 | 4.351517 | false | false | false | false |
twilio/twilio-python | twilio/rest/content/v1/content/__init__.py | 1 | 13447 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class ContentList(ListResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version):
"""
Initialize the ContentList
:param Version version: Version that contains the resource
:returns: twilio.rest.content.v1.content.ContentList
:rtype: twilio.rest.content.v1.content.ContentList
"""
super(ContentList, self).__init__(version)
# Path Solution
self._solution = {}
self._uri = '/Content'.format(**self._solution)
def create(self):
"""
Create the ContentInstance
:returns: The created ContentInstance
:rtype: twilio.rest.content.v1.content.ContentInstance
"""
payload = self._version.create(method='POST', uri=self._uri, )
return ContentInstance(self._version, payload, )
def stream(self, limit=None, page_size=None):
"""
Streams ContentInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.content.v1.content.ContentInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, limit=None, page_size=None):
"""
Lists ContentInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.content.v1.content.ContentInstance]
"""
return list(self.stream(limit=limit, page_size=page_size, ))
def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of ContentInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of ContentInstance
:rtype: twilio.rest.content.v1.content.ContentPage
"""
data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })
response = self._version.page(method='GET', uri=self._uri, params=data, )
return ContentPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of ContentInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of ContentInstance
:rtype: twilio.rest.content.v1.content.ContentPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return ContentPage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a ContentContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.content.v1.content.ContentContext
:rtype: twilio.rest.content.v1.content.ContentContext
"""
return ContentContext(self._version, sid=sid, )
def __call__(self, sid):
"""
Constructs a ContentContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.content.v1.content.ContentContext
:rtype: twilio.rest.content.v1.content.ContentContext
"""
return ContentContext(self._version, sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Content.V1.ContentList>'
class ContentPage(Page):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, response, solution):
"""
Initialize the ContentPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.content.v1.content.ContentPage
:rtype: twilio.rest.content.v1.content.ContentPage
"""
super(ContentPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of ContentInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.content.v1.content.ContentInstance
:rtype: twilio.rest.content.v1.content.ContentInstance
"""
return ContentInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Content.V1.ContentPage>'
class ContentContext(InstanceContext):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, sid):
"""
Initialize the ContentContext
:param Version version: Version that contains the resource
:param sid: The unique string that identifies the resource
:returns: twilio.rest.content.v1.content.ContentContext
:rtype: twilio.rest.content.v1.content.ContentContext
"""
super(ContentContext, self).__init__(version)
# Path Solution
self._solution = {'sid': sid, }
self._uri = '/Content/{sid}'.format(**self._solution)
def fetch(self):
"""
Fetch the ContentInstance
:returns: The fetched ContentInstance
:rtype: twilio.rest.content.v1.content.ContentInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return ContentInstance(self._version, payload, sid=self._solution['sid'], )
def delete(self):
"""
Deletes the ContentInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Content.V1.ContentContext {}>'.format(context)
class ContentInstance(InstanceResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, payload, sid=None):
"""
Initialize the ContentInstance
:returns: twilio.rest.content.v1.content.ContentInstance
:rtype: twilio.rest.content.v1.content.ContentInstance
"""
super(ContentInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'sid': payload.get('sid'),
'account_sid': payload.get('account_sid'),
'friendly_name': payload.get('friendly_name'),
'language': payload.get('language'),
'variables': payload.get('variables'),
'types': payload.get('types'),
'url': payload.get('url'),
'links': payload.get('links'),
}
# Context
self._context = None
self._solution = {'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ContentContext for this ContentInstance
:rtype: twilio.rest.content.v1.content.ContentContext
"""
if self._context is None:
self._context = ContentContext(self._version, sid=self._solution['sid'], )
return self._context
@property
def date_created(self):
"""
:returns: The RFC 2822 date and time in GMT that the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The RFC 2822 date and time in GMT that the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def friendly_name(self):
"""
:returns: A string name used to describe the Content resource
:rtype: unicode
"""
return self._properties['friendly_name']
@property
def language(self):
"""
:returns: Two-letter language code identifying the language the Content resource is in.
:rtype: unicode
"""
return self._properties['language']
@property
def variables(self):
"""
:returns: Defines the default placeholder values for variables included in the Content resource
:rtype: dict
"""
return self._properties['variables']
@property
def types(self):
"""
:returns: The Content types (e.g. twilio/text) for this Content resource
:rtype: dict
"""
return self._properties['types']
@property
def url(self):
"""
:returns: The URL of the resource, relative to `https://content.twilio.com`
:rtype: unicode
"""
return self._properties['url']
@property
def links(self):
"""
:returns: A list of links related to the Content resource
:rtype: unicode
"""
return self._properties['links']
def fetch(self):
"""
Fetch the ContentInstance
:returns: The fetched ContentInstance
:rtype: twilio.rest.content.v1.content.ContentInstance
"""
return self._proxy.fetch()
def delete(self):
"""
Deletes the ContentInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Content.V1.ContentInstance {}>'.format(context)
| mit | ddc43850da3f4f9d40c97767c3c0a9a9 | 32.533666 | 103 | 0.615751 | 4.492817 | false | false | false | false |
twilio/twilio-python | twilio/rest/voice/v1/dialing_permissions/settings.py | 1 | 8188 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class SettingsList(ListResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version):
"""
Initialize the SettingsList
:param Version version: Version that contains the resource
:returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsList
:rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsList
"""
super(SettingsList, self).__init__(version)
# Path Solution
self._solution = {}
def get(self):
"""
Constructs a SettingsContext
:returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext
:rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext
"""
return SettingsContext(self._version, )
def __call__(self):
"""
Constructs a SettingsContext
:returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext
:rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext
"""
return SettingsContext(self._version, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Voice.V1.SettingsList>'
class SettingsPage(Page):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, response, solution):
"""
Initialize the SettingsPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsPage
:rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsPage
"""
super(SettingsPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of SettingsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance
"""
return SettingsInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Voice.V1.SettingsPage>'
class SettingsContext(InstanceContext):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version):
"""
Initialize the SettingsContext
:param Version version: Version that contains the resource
:returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext
:rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext
"""
super(SettingsContext, self).__init__(version)
# Path Solution
self._solution = {}
self._uri = '/Settings'.format(**self._solution)
def fetch(self):
"""
Fetch the SettingsInstance
:returns: The fetched SettingsInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return SettingsInstance(self._version, payload, )
def update(self, dialing_permissions_inheritance=values.unset):
"""
Update the SettingsInstance
:param bool dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`
:returns: The updated SettingsInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance
"""
data = values.of({'DialingPermissionsInheritance': dialing_permissions_inheritance, })
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return SettingsInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Voice.V1.SettingsContext {}>'.format(context)
class SettingsInstance(InstanceResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, payload):
"""
Initialize the SettingsInstance
:returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance
"""
super(SettingsInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'dialing_permissions_inheritance': payload.get('dialing_permissions_inheritance'),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {}
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SettingsContext for this SettingsInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext
"""
if self._context is None:
self._context = SettingsContext(self._version, )
return self._context
@property
def dialing_permissions_inheritance(self):
"""
:returns: `true` if the sub-account will inherit voice dialing permissions from the Master Project; otherwise `false`
:rtype: bool
"""
return self._properties['dialing_permissions_inheritance']
@property
def url(self):
"""
:returns: The absolute URL of this resource
:rtype: unicode
"""
return self._properties['url']
def fetch(self):
"""
Fetch the SettingsInstance
:returns: The fetched SettingsInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance
"""
return self._proxy.fetch()
def update(self, dialing_permissions_inheritance=values.unset):
"""
Update the SettingsInstance
:param bool dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`
:returns: The updated SettingsInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance
"""
return self._proxy.update(dialing_permissions_inheritance=dialing_permissions_inheritance, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Voice.V1.SettingsInstance {}>'.format(context)
| mit | 65b0f93acac84eca9c66a246544fbcac | 32.834711 | 159 | 0.652785 | 4.423555 | false | false | false | false |
twilio/twilio-python | twilio/rest/verify/v2/safelist.py | 1 | 7938 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class SafelistList(ListResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version):
"""
Initialize the SafelistList
:param Version version: Version that contains the resource
:returns: twilio.rest.verify.v2.safelist.SafelistList
:rtype: twilio.rest.verify.v2.safelist.SafelistList
"""
super(SafelistList, self).__init__(version)
# Path Solution
self._solution = {}
self._uri = '/SafeList/Numbers'.format(**self._solution)
def create(self, phone_number):
"""
Create the SafelistInstance
:param unicode phone_number: The phone number to be added in SafeList.
:returns: The created SafelistInstance
:rtype: twilio.rest.verify.v2.safelist.SafelistInstance
"""
data = values.of({'PhoneNumber': phone_number, })
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return SafelistInstance(self._version, payload, )
def get(self, phone_number):
"""
Constructs a SafelistContext
:param phone_number: The phone number to be fetched from SafeList.
:returns: twilio.rest.verify.v2.safelist.SafelistContext
:rtype: twilio.rest.verify.v2.safelist.SafelistContext
"""
return SafelistContext(self._version, phone_number=phone_number, )
def __call__(self, phone_number):
"""
Constructs a SafelistContext
:param phone_number: The phone number to be fetched from SafeList.
:returns: twilio.rest.verify.v2.safelist.SafelistContext
:rtype: twilio.rest.verify.v2.safelist.SafelistContext
"""
return SafelistContext(self._version, phone_number=phone_number, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Verify.V2.SafelistList>'
class SafelistPage(Page):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, response, solution):
"""
Initialize the SafelistPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.verify.v2.safelist.SafelistPage
:rtype: twilio.rest.verify.v2.safelist.SafelistPage
"""
super(SafelistPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of SafelistInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.verify.v2.safelist.SafelistInstance
:rtype: twilio.rest.verify.v2.safelist.SafelistInstance
"""
return SafelistInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Verify.V2.SafelistPage>'
class SafelistContext(InstanceContext):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, phone_number):
"""
Initialize the SafelistContext
:param Version version: Version that contains the resource
:param phone_number: The phone number to be fetched from SafeList.
:returns: twilio.rest.verify.v2.safelist.SafelistContext
:rtype: twilio.rest.verify.v2.safelist.SafelistContext
"""
super(SafelistContext, self).__init__(version)
# Path Solution
self._solution = {'phone_number': phone_number, }
self._uri = '/SafeList/Numbers/{phone_number}'.format(**self._solution)
def fetch(self):
"""
Fetch the SafelistInstance
:returns: The fetched SafelistInstance
:rtype: twilio.rest.verify.v2.safelist.SafelistInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return SafelistInstance(self._version, payload, phone_number=self._solution['phone_number'], )
def delete(self):
"""
Deletes the SafelistInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Verify.V2.SafelistContext {}>'.format(context)
class SafelistInstance(InstanceResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, payload, phone_number=None):
"""
Initialize the SafelistInstance
:returns: twilio.rest.verify.v2.safelist.SafelistInstance
:rtype: twilio.rest.verify.v2.safelist.SafelistInstance
"""
super(SafelistInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'phone_number': payload.get('phone_number'),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {'phone_number': phone_number or self._properties['phone_number'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SafelistContext for this SafelistInstance
:rtype: twilio.rest.verify.v2.safelist.SafelistContext
"""
if self._context is None:
self._context = SafelistContext(self._version, phone_number=self._solution['phone_number'], )
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the resource.
:rtype: unicode
"""
return self._properties['sid']
@property
def phone_number(self):
"""
:returns: The phone number in SafeList.
:rtype: unicode
"""
return self._properties['phone_number']
@property
def url(self):
"""
:returns: The absolute URL of the SafeList resource.
:rtype: unicode
"""
return self._properties['url']
def fetch(self):
"""
Fetch the SafelistInstance
:returns: The fetched SafelistInstance
:rtype: twilio.rest.verify.v2.safelist.SafelistInstance
"""
return self._proxy.fetch()
def delete(self):
"""
Deletes the SafelistInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Verify.V2.SafelistInstance {}>'.format(context)
| mit | d7c4cc23f900fa551db46fad881fc5de | 29.530769 | 105 | 0.619678 | 4.2336 | false | false | false | false |
twilio/twilio-python | twilio/rest/video/v1/room/room_participant/room_participant_anonymize.py | 1 | 10140 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class AnonymizeList(ListResource):
def __init__(self, version, room_sid, sid):
"""
Initialize the AnonymizeList
:param Version version: Version that contains the resource
:param room_sid: The SID of the participant's room
:param sid: The unique string that identifies the resource
:returns: twilio.rest.video.v1.room.room_participant.room_participant_anonymize.AnonymizeList
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_anonymize.AnonymizeList
"""
super(AnonymizeList, self).__init__(version)
# Path Solution
self._solution = {'room_sid': room_sid, 'sid': sid, }
def get(self):
"""
Constructs a AnonymizeContext
:returns: twilio.rest.video.v1.room.room_participant.room_participant_anonymize.AnonymizeContext
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_anonymize.AnonymizeContext
"""
return AnonymizeContext(
self._version,
room_sid=self._solution['room_sid'],
sid=self._solution['sid'],
)
def __call__(self):
"""
Constructs a AnonymizeContext
:returns: twilio.rest.video.v1.room.room_participant.room_participant_anonymize.AnonymizeContext
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_anonymize.AnonymizeContext
"""
return AnonymizeContext(
self._version,
room_sid=self._solution['room_sid'],
sid=self._solution['sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Video.V1.AnonymizeList>'
class AnonymizePage(Page):
def __init__(self, version, response, solution):
"""
Initialize the AnonymizePage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param room_sid: The SID of the participant's room
:param sid: The unique string that identifies the resource
:returns: twilio.rest.video.v1.room.room_participant.room_participant_anonymize.AnonymizePage
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_anonymize.AnonymizePage
"""
super(AnonymizePage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of AnonymizeInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.video.v1.room.room_participant.room_participant_anonymize.AnonymizeInstance
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_anonymize.AnonymizeInstance
"""
return AnonymizeInstance(
self._version,
payload,
room_sid=self._solution['room_sid'],
sid=self._solution['sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Video.V1.AnonymizePage>'
class AnonymizeContext(InstanceContext):
def __init__(self, version, room_sid, sid):
"""
Initialize the AnonymizeContext
:param Version version: Version that contains the resource
:param room_sid: The SID of the room with the participant to update
:param sid: The SID that identifies the resource to update
:returns: twilio.rest.video.v1.room.room_participant.room_participant_anonymize.AnonymizeContext
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_anonymize.AnonymizeContext
"""
super(AnonymizeContext, self).__init__(version)
# Path Solution
self._solution = {'room_sid': room_sid, 'sid': sid, }
self._uri = '/Rooms/{room_sid}/Participants/{sid}/Anonymize'.format(**self._solution)
def update(self):
"""
Update the AnonymizeInstance
:returns: The updated AnonymizeInstance
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_anonymize.AnonymizeInstance
"""
payload = self._version.update(method='POST', uri=self._uri, )
return AnonymizeInstance(
self._version,
payload,
room_sid=self._solution['room_sid'],
sid=self._solution['sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Video.V1.AnonymizeContext {}>'.format(context)
class AnonymizeInstance(InstanceResource):
class Status(object):
CONNECTED = "connected"
DISCONNECTED = "disconnected"
def __init__(self, version, payload, room_sid, sid):
"""
Initialize the AnonymizeInstance
:returns: twilio.rest.video.v1.room.room_participant.room_participant_anonymize.AnonymizeInstance
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_anonymize.AnonymizeInstance
"""
super(AnonymizeInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'room_sid': payload.get('room_sid'),
'account_sid': payload.get('account_sid'),
'status': payload.get('status'),
'identity': payload.get('identity'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'start_time': deserialize.iso8601_datetime(payload.get('start_time')),
'end_time': deserialize.iso8601_datetime(payload.get('end_time')),
'duration': deserialize.integer(payload.get('duration')),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {'room_sid': room_sid, 'sid': sid, }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: AnonymizeContext for this AnonymizeInstance
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_anonymize.AnonymizeContext
"""
if self._context is None:
self._context = AnonymizeContext(
self._version,
room_sid=self._solution['room_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def room_sid(self):
"""
:returns: The SID of the participant's room
:rtype: unicode
"""
return self._properties['room_sid']
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def status(self):
"""
:returns: The status of the Participant
:rtype: AnonymizeInstance.Status
"""
return self._properties['status']
@property
def identity(self):
"""
:returns: The SID of the participant
:rtype: unicode
"""
return self._properties['identity']
@property
def date_created(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def start_time(self):
"""
:returns: The time of participant connected to the room in ISO 8601 format
:rtype: datetime
"""
return self._properties['start_time']
@property
def end_time(self):
"""
:returns: The time when the participant disconnected from the room in ISO 8601 format
:rtype: datetime
"""
return self._properties['end_time']
@property
def duration(self):
"""
:returns: Duration of time in seconds the participant was connected
:rtype: unicode
"""
return self._properties['duration']
@property
def url(self):
"""
:returns: The absolute URL of the resource
:rtype: unicode
"""
return self._properties['url']
def update(self):
"""
Update the AnonymizeInstance
:returns: The updated AnonymizeInstance
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_anonymize.AnonymizeInstance
"""
return self._proxy.update()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Video.V1.AnonymizeInstance {}>'.format(context)
| mit | af14f68442b599d1f36b5ba4fef82c2b | 30.886792 | 105 | 0.609961 | 4.152334 | false | false | false | false |
twilio/twilio-python | tests/integration/trusthub/v1/trust_products/test_trust_products_entity_assignments.py | 1 | 7330 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class TrustProductsEntityAssignmentsTestCase(IntegrationTestCase):
def test_create_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.trusthub.v1.trust_products("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.trust_products_entity_assignments.create(object_sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
values = {'ObjectSid': "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", }
self.holodeck.assert_has_request(Request(
'post',
'https://trusthub.twilio.com/v1/TrustProducts/BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/EntityAssignments',
data=values,
))
def test_create_response(self):
self.holodeck.mock(Response(
201,
'''
{
"sid": "BVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"trust_product_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"object_sid": "RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"date_created": "2019-07-31T02:34:41Z",
"url": "https://trusthub.twilio.com/v1/TrustProducts/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/EntityAssignments/BVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
'''
))
actual = self.client.trusthub.v1.trust_products("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.trust_products_entity_assignments.create(object_sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
self.assertIsNotNone(actual)
def test_list_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.trusthub.v1.trust_products("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.trust_products_entity_assignments.list()
self.holodeck.assert_has_request(Request(
'get',
'https://trusthub.twilio.com/v1/TrustProducts/BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/EntityAssignments',
))
def test_read_empty_response(self):
self.holodeck.mock(Response(
200,
'''
{
"results": [],
"meta": {
"page": 0,
"page_size": 50,
"first_page_url": "https://trusthub.twilio.com/v1/TrustProducts/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/EntityAssignments?PageSize=50&Page=0",
"previous_page_url": null,
"url": "https://trusthub.twilio.com/v1/TrustProducts/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/EntityAssignments?PageSize=50&Page=0",
"next_page_url": null,
"key": "results"
}
}
'''
))
actual = self.client.trusthub.v1.trust_products("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.trust_products_entity_assignments.list()
self.assertIsNotNone(actual)
def test_read_full_response(self):
self.holodeck.mock(Response(
200,
'''
{
"results": [
{
"sid": "BVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"trust_product_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"object_sid": "RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"date_created": "2019-07-31T02:34:41Z",
"url": "https://trusthub.twilio.com/v1/TrustProducts/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/EntityAssignments/BVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
],
"meta": {
"page": 0,
"page_size": 50,
"first_page_url": "https://trusthub.twilio.com/v1/TrustProducts/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/EntityAssignments?PageSize=50&Page=0",
"previous_page_url": null,
"url": "https://trusthub.twilio.com/v1/TrustProducts/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/EntityAssignments?PageSize=50&Page=0",
"next_page_url": null,
"key": "results"
}
}
'''
))
actual = self.client.trusthub.v1.trust_products("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.trust_products_entity_assignments.list()
self.assertIsNotNone(actual)
def test_fetch_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.trusthub.v1.trust_products("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.trust_products_entity_assignments("BVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()
self.holodeck.assert_has_request(Request(
'get',
'https://trusthub.twilio.com/v1/TrustProducts/BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/EntityAssignments/BVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
))
def test_fetch_response(self):
self.holodeck.mock(Response(
200,
'''
{
"sid": "BVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"trust_product_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"object_sid": "RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"date_created": "2019-07-31T02:34:41Z",
"url": "https://trusthub.twilio.com/v1/TrustProducts/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/EntityAssignments/BVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
'''
))
actual = self.client.trusthub.v1.trust_products("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.trust_products_entity_assignments("BVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()
self.assertIsNotNone(actual)
def test_delete_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.trusthub.v1.trust_products("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.trust_products_entity_assignments("BVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete()
self.holodeck.assert_has_request(Request(
'delete',
'https://trusthub.twilio.com/v1/TrustProducts/BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/EntityAssignments/BVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
))
def test_delete_response(self):
self.holodeck.mock(Response(
204,
None,
))
actual = self.client.trusthub.v1.trust_products("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.trust_products_entity_assignments("BVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete()
self.assertTrue(actual)
| mit | 2dd821dfd09cc3c908ff1102e32a4445 | 41.126437 | 165 | 0.591542 | 4.642179 | false | true | false | false |
twilio/twilio-python | twilio/rest/voice/v1/dialing_permissions/country/__init__.py | 1 | 18110 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
from twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix import HighriskSpecialPrefixList
class CountryList(ListResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version):
"""
Initialize the CountryList
:param Version version: Version that contains the resource
:returns: twilio.rest.voice.v1.dialing_permissions.country.CountryList
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryList
"""
super(CountryList, self).__init__(version)
# Path Solution
self._solution = {}
self._uri = '/DialingPermissions/Countries'.format(**self._solution)
def stream(self, iso_code=values.unset, continent=values.unset,
country_code=values.unset, low_risk_numbers_enabled=values.unset,
high_risk_special_numbers_enabled=values.unset,
high_risk_tollfraud_numbers_enabled=values.unset, limit=None,
page_size=None):
"""
Streams CountryInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param unicode iso_code: Filter to retrieve the country permissions by specifying the ISO country code
:param unicode continent: Filter to retrieve the country permissions by specifying the continent
:param unicode country_code: Country code filter
:param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled
:param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled
:param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk toll fraud numbers enabled
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.voice.v1.dialing_permissions.country.CountryInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(
iso_code=iso_code,
continent=continent,
country_code=country_code,
low_risk_numbers_enabled=low_risk_numbers_enabled,
high_risk_special_numbers_enabled=high_risk_special_numbers_enabled,
high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled,
page_size=limits['page_size'],
)
return self._version.stream(page, limits['limit'])
def list(self, iso_code=values.unset, continent=values.unset,
country_code=values.unset, low_risk_numbers_enabled=values.unset,
high_risk_special_numbers_enabled=values.unset,
high_risk_tollfraud_numbers_enabled=values.unset, limit=None,
page_size=None):
"""
Lists CountryInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param unicode iso_code: Filter to retrieve the country permissions by specifying the ISO country code
:param unicode continent: Filter to retrieve the country permissions by specifying the continent
:param unicode country_code: Country code filter
:param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled
:param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled
:param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk toll fraud numbers enabled
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.voice.v1.dialing_permissions.country.CountryInstance]
"""
return list(self.stream(
iso_code=iso_code,
continent=continent,
country_code=country_code,
low_risk_numbers_enabled=low_risk_numbers_enabled,
high_risk_special_numbers_enabled=high_risk_special_numbers_enabled,
high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled,
limit=limit,
page_size=page_size,
))
def page(self, iso_code=values.unset, continent=values.unset,
country_code=values.unset, low_risk_numbers_enabled=values.unset,
high_risk_special_numbers_enabled=values.unset,
high_risk_tollfraud_numbers_enabled=values.unset,
page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of CountryInstance records from the API.
Request is executed immediately
:param unicode iso_code: Filter to retrieve the country permissions by specifying the ISO country code
:param unicode continent: Filter to retrieve the country permissions by specifying the continent
:param unicode country_code: Country code filter
:param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled
:param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled
:param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk toll fraud numbers enabled
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of CountryInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryPage
"""
data = values.of({
'IsoCode': iso_code,
'Continent': continent,
'CountryCode': country_code,
'LowRiskNumbersEnabled': low_risk_numbers_enabled,
'HighRiskSpecialNumbersEnabled': high_risk_special_numbers_enabled,
'HighRiskTollfraudNumbersEnabled': high_risk_tollfraud_numbers_enabled,
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(method='GET', uri=self._uri, params=data, )
return CountryPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of CountryInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of CountryInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return CountryPage(self._version, response, self._solution)
def get(self, iso_code):
"""
Constructs a CountryContext
:param iso_code: The ISO country code
:returns: twilio.rest.voice.v1.dialing_permissions.country.CountryContext
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryContext
"""
return CountryContext(self._version, iso_code=iso_code, )
def __call__(self, iso_code):
"""
Constructs a CountryContext
:param iso_code: The ISO country code
:returns: twilio.rest.voice.v1.dialing_permissions.country.CountryContext
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryContext
"""
return CountryContext(self._version, iso_code=iso_code, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Voice.V1.CountryList>'
class CountryPage(Page):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, response, solution):
"""
Initialize the CountryPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.voice.v1.dialing_permissions.country.CountryPage
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryPage
"""
super(CountryPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of CountryInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance
"""
return CountryInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Voice.V1.CountryPage>'
class CountryContext(InstanceContext):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, iso_code):
"""
Initialize the CountryContext
:param Version version: Version that contains the resource
:param iso_code: The ISO country code
:returns: twilio.rest.voice.v1.dialing_permissions.country.CountryContext
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryContext
"""
super(CountryContext, self).__init__(version)
# Path Solution
self._solution = {'iso_code': iso_code, }
self._uri = '/DialingPermissions/Countries/{iso_code}'.format(**self._solution)
# Dependents
self._highrisk_special_prefixes = None
def fetch(self):
"""
Fetch the CountryInstance
:returns: The fetched CountryInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return CountryInstance(self._version, payload, iso_code=self._solution['iso_code'], )
@property
def highrisk_special_prefixes(self):
"""
Access the highrisk_special_prefixes
:returns: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList
:rtype: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList
"""
if self._highrisk_special_prefixes is None:
self._highrisk_special_prefixes = HighriskSpecialPrefixList(
self._version,
iso_code=self._solution['iso_code'],
)
return self._highrisk_special_prefixes
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Voice.V1.CountryContext {}>'.format(context)
class CountryInstance(InstanceResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, payload, iso_code=None):
"""
Initialize the CountryInstance
:returns: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance
"""
super(CountryInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'iso_code': payload.get('iso_code'),
'name': payload.get('name'),
'continent': payload.get('continent'),
'country_codes': payload.get('country_codes'),
'low_risk_numbers_enabled': payload.get('low_risk_numbers_enabled'),
'high_risk_special_numbers_enabled': payload.get('high_risk_special_numbers_enabled'),
'high_risk_tollfraud_numbers_enabled': payload.get('high_risk_tollfraud_numbers_enabled'),
'url': payload.get('url'),
'links': payload.get('links'),
}
# Context
self._context = None
self._solution = {'iso_code': iso_code or self._properties['iso_code'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: CountryContext for this CountryInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryContext
"""
if self._context is None:
self._context = CountryContext(self._version, iso_code=self._solution['iso_code'], )
return self._context
@property
def iso_code(self):
"""
:returns: The ISO country code
:rtype: unicode
"""
return self._properties['iso_code']
@property
def name(self):
"""
:returns: The name of the country
:rtype: unicode
"""
return self._properties['name']
@property
def continent(self):
"""
:returns: The name of the continent in which the country is located
:rtype: unicode
"""
return self._properties['continent']
@property
def country_codes(self):
"""
:returns: The E.164 assigned country codes(s)
:rtype: list[unicode]
"""
return self._properties['country_codes']
@property
def low_risk_numbers_enabled(self):
"""
:returns: Whether dialing to low-risk numbers is enabled
:rtype: bool
"""
return self._properties['low_risk_numbers_enabled']
@property
def high_risk_special_numbers_enabled(self):
"""
:returns: Whether dialing to high-risk special services numbers is enabled
:rtype: bool
"""
return self._properties['high_risk_special_numbers_enabled']
@property
def high_risk_tollfraud_numbers_enabled(self):
"""
:returns: Whether dialing to high-risk toll fraud numbers is enabled, else `false`
:rtype: bool
"""
return self._properties['high_risk_tollfraud_numbers_enabled']
@property
def url(self):
"""
:returns: The absolute URL of this resource
:rtype: unicode
"""
return self._properties['url']
@property
def links(self):
"""
:returns: A list of URLs related to this resource
:rtype: unicode
"""
return self._properties['links']
def fetch(self):
"""
Fetch the CountryInstance
:returns: The fetched CountryInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance
"""
return self._proxy.fetch()
@property
def highrisk_special_prefixes(self):
"""
Access the highrisk_special_prefixes
:returns: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList
:rtype: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList
"""
return self._proxy.highrisk_special_prefixes
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Voice.V1.CountryInstance {}>'.format(context)
| mit | f9bc90e5e7649c1a79c9f983056a2dd1 | 39.424107 | 155 | 0.648647 | 4.318073 | false | false | false | false |
twilio/twilio-python | twilio/rest/serverless/v1/service/environment/variable.py | 1 | 16891 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class VariableList(ListResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, service_sid, environment_sid):
"""
Initialize the VariableList
:param Version version: Version that contains the resource
:param service_sid: The SID of the Service that the Variable resource is associated with
:param environment_sid: The SID of the Environment in which the Variable exists
:returns: twilio.rest.serverless.v1.service.environment.variable.VariableList
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableList
"""
super(VariableList, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, 'environment_sid': environment_sid, }
self._uri = '/Services/{service_sid}/Environments/{environment_sid}/Variables'.format(**self._solution)
def stream(self, limit=None, page_size=None):
"""
Streams VariableInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.serverless.v1.service.environment.variable.VariableInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, limit=None, page_size=None):
"""
Lists VariableInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.serverless.v1.service.environment.variable.VariableInstance]
"""
return list(self.stream(limit=limit, page_size=page_size, ))
def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of VariableInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariablePage
"""
data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })
response = self._version.page(method='GET', uri=self._uri, params=data, )
return VariablePage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of VariableInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariablePage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return VariablePage(self._version, response, self._solution)
def create(self, key, value):
"""
Create the VariableInstance
:param unicode key: A string by which the Variable resource can be referenced
:param unicode value: A string that contains the actual value of the Variable
:returns: The created VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
"""
data = values.of({'Key': key, 'Value': value, })
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return VariableInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
)
def get(self, sid):
"""
Constructs a VariableContext
:param sid: The SID of the Variable resource to fetch
:returns: twilio.rest.serverless.v1.service.environment.variable.VariableContext
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableContext
"""
return VariableContext(
self._version,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
sid=sid,
)
def __call__(self, sid):
"""
Constructs a VariableContext
:param sid: The SID of the Variable resource to fetch
:returns: twilio.rest.serverless.v1.service.environment.variable.VariableContext
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableContext
"""
return VariableContext(
self._version,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
sid=sid,
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Serverless.V1.VariableList>'
class VariablePage(Page):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, response, solution):
"""
Initialize the VariablePage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param service_sid: The SID of the Service that the Variable resource is associated with
:param environment_sid: The SID of the Environment in which the Variable exists
:returns: twilio.rest.serverless.v1.service.environment.variable.VariablePage
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariablePage
"""
super(VariablePage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of VariableInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
"""
return VariableInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Serverless.V1.VariablePage>'
class VariableContext(InstanceContext):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, service_sid, environment_sid, sid):
"""
Initialize the VariableContext
:param Version version: Version that contains the resource
:param service_sid: The SID of the Service to fetch the Variable resource from
:param environment_sid: The SID of the Environment with the Variable resource to fetch
:param sid: The SID of the Variable resource to fetch
:returns: twilio.rest.serverless.v1.service.environment.variable.VariableContext
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableContext
"""
super(VariableContext, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, 'environment_sid': environment_sid, 'sid': sid, }
self._uri = '/Services/{service_sid}/Environments/{environment_sid}/Variables/{sid}'.format(**self._solution)
def fetch(self):
"""
Fetch the VariableInstance
:returns: The fetched VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return VariableInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
sid=self._solution['sid'],
)
def update(self, key=values.unset, value=values.unset):
"""
Update the VariableInstance
:param unicode key: A string by which the Variable resource can be referenced
:param unicode value: A string that contains the actual value of the Variable
:returns: The updated VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
"""
data = values.of({'Key': key, 'Value': value, })
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return VariableInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
sid=self._solution['sid'],
)
def delete(self):
"""
Deletes the VariableInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Serverless.V1.VariableContext {}>'.format(context)
class VariableInstance(InstanceResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, payload, service_sid, environment_sid, sid=None):
"""
Initialize the VariableInstance
:returns: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
"""
super(VariableInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'account_sid': payload.get('account_sid'),
'service_sid': payload.get('service_sid'),
'environment_sid': payload.get('environment_sid'),
'key': payload.get('key'),
'value': payload.get('value'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {
'service_sid': service_sid,
'environment_sid': environment_sid,
'sid': sid or self._properties['sid'],
}
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: VariableContext for this VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableContext
"""
if self._context is None:
self._context = VariableContext(
self._version,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the Variable resource
:rtype: unicode
"""
return self._properties['sid']
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the Variable resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def service_sid(self):
"""
:returns: The SID of the Service that the Variable resource is associated with
:rtype: unicode
"""
return self._properties['service_sid']
@property
def environment_sid(self):
"""
:returns: The SID of the Environment in which the Variable exists
:rtype: unicode
"""
return self._properties['environment_sid']
@property
def key(self):
"""
:returns: A string by which the Variable resource can be referenced
:rtype: unicode
"""
return self._properties['key']
@property
def value(self):
"""
:returns: A string that contains the actual value of the Variable
:rtype: unicode
"""
return self._properties['value']
@property
def date_created(self):
"""
:returns: The ISO 8601 date and time in GMT when the Variable resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The ISO 8601 date and time in GMT when the Variable resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def url(self):
"""
:returns: The absolute URL of the Variable resource
:rtype: unicode
"""
return self._properties['url']
def fetch(self):
"""
Fetch the VariableInstance
:returns: The fetched VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
"""
return self._proxy.fetch()
def update(self, key=values.unset, value=values.unset):
"""
Update the VariableInstance
:param unicode key: A string by which the Variable resource can be referenced
:param unicode value: A string that contains the actual value of the Variable
:returns: The updated VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
"""
return self._proxy.update(key=key, value=value, )
def delete(self):
"""
Deletes the VariableInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Serverless.V1.VariableInstance {}>'.format(context)
| mit | 2154749bff1697a55e002418dcf8fa12 | 35.09188 | 117 | 0.624119 | 4.545479 | false | false | false | false |
twilio/twilio-python | twilio/rest/notify/v1/__init__.py | 2 | 1298 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base.version import Version
from twilio.rest.notify.v1.credential import CredentialList
from twilio.rest.notify.v1.service import ServiceList
class V1(Version):
def __init__(self, domain):
"""
Initialize the V1 version of Notify
:returns: V1 version of Notify
:rtype: twilio.rest.notify.v1.V1.V1
"""
super(V1, self).__init__(domain)
self.version = 'v1'
self._credentials = None
self._services = None
@property
def credentials(self):
"""
:rtype: twilio.rest.notify.v1.credential.CredentialList
"""
if self._credentials is None:
self._credentials = CredentialList(self)
return self._credentials
@property
def services(self):
"""
:rtype: twilio.rest.notify.v1.service.ServiceList
"""
if self._services is None:
self._services = ServiceList(self)
return self._services
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Notify.V1>'
| mit | d08b1e2d208f6257800115c23a1b40c1 | 23.490566 | 63 | 0.565485 | 3.840237 | false | false | false | false |
twilio/twilio-python | twilio/rest/media/v1/player_streamer/__init__.py | 1 | 17141 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
from twilio.rest.media.v1.player_streamer.playback_grant import PlaybackGrantList
class PlayerStreamerList(ListResource):
def __init__(self, version):
"""
Initialize the PlayerStreamerList
:param Version version: Version that contains the resource
:returns: twilio.rest.media.v1.player_streamer.PlayerStreamerList
:rtype: twilio.rest.media.v1.player_streamer.PlayerStreamerList
"""
super(PlayerStreamerList, self).__init__(version)
# Path Solution
self._solution = {}
self._uri = '/PlayerStreamers'.format(**self._solution)
def create(self, video=values.unset, status_callback=values.unset,
status_callback_method=values.unset, max_duration=values.unset):
"""
Create the PlayerStreamerInstance
:param bool video: Whether the PlayerStreamer is configured to stream video
:param unicode status_callback: The URL to which Twilio will send PlayerStreamer event updates
:param unicode status_callback_method: The HTTP method Twilio should use to call the `status_callback` URL
:param unicode max_duration: Maximum PlayerStreamer duration in seconds
:returns: The created PlayerStreamerInstance
:rtype: twilio.rest.media.v1.player_streamer.PlayerStreamerInstance
"""
data = values.of({
'Video': video,
'StatusCallback': status_callback,
'StatusCallbackMethod': status_callback_method,
'MaxDuration': max_duration,
})
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return PlayerStreamerInstance(self._version, payload, )
def stream(self, order=values.unset, status=values.unset, limit=None,
page_size=None):
"""
Streams PlayerStreamerInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param PlayerStreamerInstance.Order order: The sort order of the list
:param PlayerStreamerInstance.Status status: Status to filter by
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.media.v1.player_streamer.PlayerStreamerInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(order=order, status=status, page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, order=values.unset, status=values.unset, limit=None,
page_size=None):
"""
Lists PlayerStreamerInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param PlayerStreamerInstance.Order order: The sort order of the list
:param PlayerStreamerInstance.Status status: Status to filter by
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.media.v1.player_streamer.PlayerStreamerInstance]
"""
return list(self.stream(order=order, status=status, limit=limit, page_size=page_size, ))
def page(self, order=values.unset, status=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
"""
Retrieve a single page of PlayerStreamerInstance records from the API.
Request is executed immediately
:param PlayerStreamerInstance.Order order: The sort order of the list
:param PlayerStreamerInstance.Status status: Status to filter by
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of PlayerStreamerInstance
:rtype: twilio.rest.media.v1.player_streamer.PlayerStreamerPage
"""
data = values.of({
'Order': order,
'Status': status,
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(method='GET', uri=self._uri, params=data, )
return PlayerStreamerPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of PlayerStreamerInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of PlayerStreamerInstance
:rtype: twilio.rest.media.v1.player_streamer.PlayerStreamerPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return PlayerStreamerPage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a PlayerStreamerContext
:param sid: The SID that identifies the resource to fetch
:returns: twilio.rest.media.v1.player_streamer.PlayerStreamerContext
:rtype: twilio.rest.media.v1.player_streamer.PlayerStreamerContext
"""
return PlayerStreamerContext(self._version, sid=sid, )
def __call__(self, sid):
"""
Constructs a PlayerStreamerContext
:param sid: The SID that identifies the resource to fetch
:returns: twilio.rest.media.v1.player_streamer.PlayerStreamerContext
:rtype: twilio.rest.media.v1.player_streamer.PlayerStreamerContext
"""
return PlayerStreamerContext(self._version, sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Media.V1.PlayerStreamerList>'
class PlayerStreamerPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the PlayerStreamerPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.media.v1.player_streamer.PlayerStreamerPage
:rtype: twilio.rest.media.v1.player_streamer.PlayerStreamerPage
"""
super(PlayerStreamerPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of PlayerStreamerInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.media.v1.player_streamer.PlayerStreamerInstance
:rtype: twilio.rest.media.v1.player_streamer.PlayerStreamerInstance
"""
return PlayerStreamerInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Media.V1.PlayerStreamerPage>'
class PlayerStreamerContext(InstanceContext):
def __init__(self, version, sid):
"""
Initialize the PlayerStreamerContext
:param Version version: Version that contains the resource
:param sid: The SID that identifies the resource to fetch
:returns: twilio.rest.media.v1.player_streamer.PlayerStreamerContext
:rtype: twilio.rest.media.v1.player_streamer.PlayerStreamerContext
"""
super(PlayerStreamerContext, self).__init__(version)
# Path Solution
self._solution = {'sid': sid, }
self._uri = '/PlayerStreamers/{sid}'.format(**self._solution)
# Dependents
self._playback_grant = None
def fetch(self):
"""
Fetch the PlayerStreamerInstance
:returns: The fetched PlayerStreamerInstance
:rtype: twilio.rest.media.v1.player_streamer.PlayerStreamerInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return PlayerStreamerInstance(self._version, payload, sid=self._solution['sid'], )
def update(self, status):
"""
Update the PlayerStreamerInstance
:param PlayerStreamerInstance.UpdateStatus status: The status the PlayerStreamer should be transitioned to
:returns: The updated PlayerStreamerInstance
:rtype: twilio.rest.media.v1.player_streamer.PlayerStreamerInstance
"""
data = values.of({'Status': status, })
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return PlayerStreamerInstance(self._version, payload, sid=self._solution['sid'], )
@property
def playback_grant(self):
"""
Access the playback_grant
:returns: twilio.rest.media.v1.player_streamer.playback_grant.PlaybackGrantList
:rtype: twilio.rest.media.v1.player_streamer.playback_grant.PlaybackGrantList
"""
if self._playback_grant is None:
self._playback_grant = PlaybackGrantList(self._version, sid=self._solution['sid'], )
return self._playback_grant
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Media.V1.PlayerStreamerContext {}>'.format(context)
class PlayerStreamerInstance(InstanceResource):
class Status(object):
CREATED = "created"
STARTED = "started"
ENDED = "ended"
FAILED = "failed"
class UpdateStatus(object):
ENDED = "ended"
class Order(object):
ASC = "asc"
DESC = "desc"
class EndedReason(object):
ENDED_VIA_API = "ended-via-api"
MAX_DURATION_EXCEEDED = "max-duration-exceeded"
STREAM_DISCONNECTED_BY_SOURCE = "stream-disconnected-by-source"
UNEXPECTED_FAILURE = "unexpected-failure"
def __init__(self, version, payload, sid=None):
"""
Initialize the PlayerStreamerInstance
:returns: twilio.rest.media.v1.player_streamer.PlayerStreamerInstance
:rtype: twilio.rest.media.v1.player_streamer.PlayerStreamerInstance
"""
super(PlayerStreamerInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'account_sid': payload.get('account_sid'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'video': payload.get('video'),
'links': payload.get('links'),
'sid': payload.get('sid'),
'status': payload.get('status'),
'url': payload.get('url'),
'status_callback': payload.get('status_callback'),
'status_callback_method': payload.get('status_callback_method'),
'ended_reason': payload.get('ended_reason'),
'max_duration': deserialize.integer(payload.get('max_duration')),
}
# Context
self._context = None
self._solution = {'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: PlayerStreamerContext for this PlayerStreamerInstance
:rtype: twilio.rest.media.v1.player_streamer.PlayerStreamerContext
"""
if self._context is None:
self._context = PlayerStreamerContext(self._version, sid=self._solution['sid'], )
return self._context
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def date_created(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def video(self):
"""
:returns: Whether the PlayerStreamer is configured to stream video
:rtype: bool
"""
return self._properties['video']
@property
def links(self):
"""
:returns: The URLs of related resources
:rtype: unicode
"""
return self._properties['links']
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def status(self):
"""
:returns: The status of the PlayerStreamer
:rtype: PlayerStreamerInstance.Status
"""
return self._properties['status']
@property
def url(self):
"""
:returns: The absolute URL of the resource
:rtype: unicode
"""
return self._properties['url']
@property
def status_callback(self):
"""
:returns: The URL to which Twilio will send PlayerStreamer event updates
:rtype: unicode
"""
return self._properties['status_callback']
@property
def status_callback_method(self):
"""
:returns: The HTTP method Twilio should use to call the `status_callback` URL
:rtype: unicode
"""
return self._properties['status_callback_method']
@property
def ended_reason(self):
"""
:returns: The reason why a PlayerStreamer ended
:rtype: PlayerStreamerInstance.EndedReason
"""
return self._properties['ended_reason']
@property
def max_duration(self):
"""
:returns: Maximum PlayerStreamer duration in seconds
:rtype: unicode
"""
return self._properties['max_duration']
def fetch(self):
"""
Fetch the PlayerStreamerInstance
:returns: The fetched PlayerStreamerInstance
:rtype: twilio.rest.media.v1.player_streamer.PlayerStreamerInstance
"""
return self._proxy.fetch()
def update(self, status):
"""
Update the PlayerStreamerInstance
:param PlayerStreamerInstance.UpdateStatus status: The status the PlayerStreamer should be transitioned to
:returns: The updated PlayerStreamerInstance
:rtype: twilio.rest.media.v1.player_streamer.PlayerStreamerInstance
"""
return self._proxy.update(status, )
@property
def playback_grant(self):
"""
Access the playback_grant
:returns: twilio.rest.media.v1.player_streamer.playback_grant.PlaybackGrantList
:rtype: twilio.rest.media.v1.player_streamer.playback_grant.PlaybackGrantList
"""
return self._proxy.playback_grant
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Media.V1.PlayerStreamerInstance {}>'.format(context)
| mit | 2024e8e4093db5477c655c63a17b2a70 | 34.197125 | 114 | 0.632285 | 4.28954 | false | false | false | false |
twilio/twilio-python | twilio/rest/studio/v1/flow/execution/__init__.py | 1 | 18388 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
from twilio.rest.studio.v1.flow.execution.execution_context import ExecutionContextList
from twilio.rest.studio.v1.flow.execution.execution_step import ExecutionStepList
class ExecutionList(ListResource):
def __init__(self, version, flow_sid):
"""
Initialize the ExecutionList
:param Version version: Version that contains the resource
:param flow_sid: The SID of the Flow
:returns: twilio.rest.studio.v1.flow.execution.ExecutionList
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionList
"""
super(ExecutionList, self).__init__(version)
# Path Solution
self._solution = {'flow_sid': flow_sid, }
self._uri = '/Flows/{flow_sid}/Executions'.format(**self._solution)
def stream(self, date_created_from=values.unset, date_created_to=values.unset,
limit=None, page_size=None):
"""
Streams ExecutionInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param datetime date_created_from: Only show Executions that started on or after this ISO 8601 date-time
:param datetime date_created_to: Only show Executions that started before this ISO 8601 date-time
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.studio.v1.flow.execution.ExecutionInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(
date_created_from=date_created_from,
date_created_to=date_created_to,
page_size=limits['page_size'],
)
return self._version.stream(page, limits['limit'])
def list(self, date_created_from=values.unset, date_created_to=values.unset,
limit=None, page_size=None):
"""
Lists ExecutionInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param datetime date_created_from: Only show Executions that started on or after this ISO 8601 date-time
:param datetime date_created_to: Only show Executions that started before this ISO 8601 date-time
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.studio.v1.flow.execution.ExecutionInstance]
"""
return list(self.stream(
date_created_from=date_created_from,
date_created_to=date_created_to,
limit=limit,
page_size=page_size,
))
def page(self, date_created_from=values.unset, date_created_to=values.unset,
page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of ExecutionInstance records from the API.
Request is executed immediately
:param datetime date_created_from: Only show Executions that started on or after this ISO 8601 date-time
:param datetime date_created_to: Only show Executions that started before this ISO 8601 date-time
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of ExecutionInstance
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionPage
"""
data = values.of({
'DateCreatedFrom': serialize.iso8601_datetime(date_created_from),
'DateCreatedTo': serialize.iso8601_datetime(date_created_to),
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(method='GET', uri=self._uri, params=data, )
return ExecutionPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of ExecutionInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of ExecutionInstance
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return ExecutionPage(self._version, response, self._solution)
def create(self, to, from_, parameters=values.unset):
"""
Create the ExecutionInstance
:param unicode to: The Contact phone number to start a Studio Flow Execution
:param unicode from_: The Twilio phone number or Messaging Service SID to send messages or initiate calls from during the Flow Execution
:param dict parameters: JSON data that will be added to the Flow's context
:returns: The created ExecutionInstance
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance
"""
data = values.of({'To': to, 'From': from_, 'Parameters': serialize.object(parameters), })
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return ExecutionInstance(self._version, payload, flow_sid=self._solution['flow_sid'], )
def get(self, sid):
"""
Constructs a ExecutionContext
:param sid: The SID of the Execution resource to fetch
:returns: twilio.rest.studio.v1.flow.execution.ExecutionContext
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionContext
"""
return ExecutionContext(self._version, flow_sid=self._solution['flow_sid'], sid=sid, )
def __call__(self, sid):
"""
Constructs a ExecutionContext
:param sid: The SID of the Execution resource to fetch
:returns: twilio.rest.studio.v1.flow.execution.ExecutionContext
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionContext
"""
return ExecutionContext(self._version, flow_sid=self._solution['flow_sid'], sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Studio.V1.ExecutionList>'
class ExecutionPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the ExecutionPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param flow_sid: The SID of the Flow
:returns: twilio.rest.studio.v1.flow.execution.ExecutionPage
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionPage
"""
super(ExecutionPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of ExecutionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.studio.v1.flow.execution.ExecutionInstance
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance
"""
return ExecutionInstance(self._version, payload, flow_sid=self._solution['flow_sid'], )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Studio.V1.ExecutionPage>'
class ExecutionContext(InstanceContext):
def __init__(self, version, flow_sid, sid):
"""
Initialize the ExecutionContext
:param Version version: Version that contains the resource
:param flow_sid: The SID of the Flow
:param sid: The SID of the Execution resource to fetch
:returns: twilio.rest.studio.v1.flow.execution.ExecutionContext
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionContext
"""
super(ExecutionContext, self).__init__(version)
# Path Solution
self._solution = {'flow_sid': flow_sid, 'sid': sid, }
self._uri = '/Flows/{flow_sid}/Executions/{sid}'.format(**self._solution)
# Dependents
self._steps = None
self._execution_context = None
def fetch(self):
"""
Fetch the ExecutionInstance
:returns: The fetched ExecutionInstance
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return ExecutionInstance(
self._version,
payload,
flow_sid=self._solution['flow_sid'],
sid=self._solution['sid'],
)
def delete(self):
"""
Deletes the ExecutionInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def update(self, status):
"""
Update the ExecutionInstance
:param ExecutionInstance.Status status: The status of the Execution
:returns: The updated ExecutionInstance
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance
"""
data = values.of({'Status': status, })
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return ExecutionInstance(
self._version,
payload,
flow_sid=self._solution['flow_sid'],
sid=self._solution['sid'],
)
@property
def steps(self):
"""
Access the steps
:returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepList
:rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepList
"""
if self._steps is None:
self._steps = ExecutionStepList(
self._version,
flow_sid=self._solution['flow_sid'],
execution_sid=self._solution['sid'],
)
return self._steps
@property
def execution_context(self):
"""
Access the execution_context
:returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList
:rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList
"""
if self._execution_context is None:
self._execution_context = ExecutionContextList(
self._version,
flow_sid=self._solution['flow_sid'],
execution_sid=self._solution['sid'],
)
return self._execution_context
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Studio.V1.ExecutionContext {}>'.format(context)
class ExecutionInstance(InstanceResource):
class Status(object):
ACTIVE = "active"
ENDED = "ended"
def __init__(self, version, payload, flow_sid, sid=None):
"""
Initialize the ExecutionInstance
:returns: twilio.rest.studio.v1.flow.execution.ExecutionInstance
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance
"""
super(ExecutionInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'account_sid': payload.get('account_sid'),
'flow_sid': payload.get('flow_sid'),
'contact_sid': payload.get('contact_sid'),
'contact_channel_address': payload.get('contact_channel_address'),
'context': payload.get('context'),
'status': payload.get('status'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'url': payload.get('url'),
'links': payload.get('links'),
}
# Context
self._context = None
self._solution = {'flow_sid': flow_sid, 'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ExecutionContext for this ExecutionInstance
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionContext
"""
if self._context is None:
self._context = ExecutionContext(
self._version,
flow_sid=self._solution['flow_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def flow_sid(self):
"""
:returns: The SID of the Flow
:rtype: unicode
"""
return self._properties['flow_sid']
@property
def contact_sid(self):
"""
:returns: The SID of the Contact
:rtype: unicode
"""
return self._properties['contact_sid']
@property
def contact_channel_address(self):
"""
:returns: The phone number, SIP address or Client identifier that triggered the Execution
:rtype: unicode
"""
return self._properties['contact_channel_address']
@property
def context(self):
"""
:returns: The current state of the flow
:rtype: dict
"""
return self._properties['context']
@property
def status(self):
"""
:returns: The status of the Execution
:rtype: ExecutionInstance.Status
"""
return self._properties['status']
@property
def date_created(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def url(self):
"""
:returns: The absolute URL of the resource
:rtype: unicode
"""
return self._properties['url']
@property
def links(self):
"""
:returns: Nested resource URLs
:rtype: unicode
"""
return self._properties['links']
def fetch(self):
"""
Fetch the ExecutionInstance
:returns: The fetched ExecutionInstance
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance
"""
return self._proxy.fetch()
def delete(self):
"""
Deletes the ExecutionInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def update(self, status):
"""
Update the ExecutionInstance
:param ExecutionInstance.Status status: The status of the Execution
:returns: The updated ExecutionInstance
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance
"""
return self._proxy.update(status, )
@property
def steps(self):
"""
Access the steps
:returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepList
:rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepList
"""
return self._proxy.steps
@property
def execution_context(self):
"""
Access the execution_context
:returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList
:rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList
"""
return self._proxy.execution_context
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Studio.V1.ExecutionInstance {}>'.format(context)
| mit | a815d50b1d6749538587fa5a97baf495 | 33.434457 | 144 | 0.615293 | 4.391689 | false | false | false | false |
twilio/twilio-python | twilio/rest/notify/v1/credential.py | 1 | 16655 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class CredentialList(ListResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version):
"""
Initialize the CredentialList
:param Version version: Version that contains the resource
:returns: twilio.rest.notify.v1.credential.CredentialList
:rtype: twilio.rest.notify.v1.credential.CredentialList
"""
super(CredentialList, self).__init__(version)
# Path Solution
self._solution = {}
self._uri = '/Credentials'.format(**self._solution)
def stream(self, limit=None, page_size=None):
"""
Streams CredentialInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.notify.v1.credential.CredentialInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, limit=None, page_size=None):
"""
Lists CredentialInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.notify.v1.credential.CredentialInstance]
"""
return list(self.stream(limit=limit, page_size=page_size, ))
def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of CredentialInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of CredentialInstance
:rtype: twilio.rest.notify.v1.credential.CredentialPage
"""
data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })
response = self._version.page(method='GET', uri=self._uri, params=data, )
return CredentialPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of CredentialInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of CredentialInstance
:rtype: twilio.rest.notify.v1.credential.CredentialPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return CredentialPage(self._version, response, self._solution)
def create(self, type, friendly_name=values.unset, certificate=values.unset,
private_key=values.unset, sandbox=values.unset, api_key=values.unset,
secret=values.unset):
"""
Create the CredentialInstance
:param CredentialInstance.PushService type: The Credential type
:param unicode friendly_name: A string to describe the resource
:param unicode certificate: [APN only] The URL-encoded representation of the certificate
:param unicode private_key: [APN only] URL-encoded representation of the private key
:param bool sandbox: [APN only] Whether to send the credential to sandbox APNs
:param unicode api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging
:param unicode secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging
:returns: The created CredentialInstance
:rtype: twilio.rest.notify.v1.credential.CredentialInstance
"""
data = values.of({
'Type': type,
'FriendlyName': friendly_name,
'Certificate': certificate,
'PrivateKey': private_key,
'Sandbox': sandbox,
'ApiKey': api_key,
'Secret': secret,
})
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return CredentialInstance(self._version, payload, )
def get(self, sid):
"""
Constructs a CredentialContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.notify.v1.credential.CredentialContext
:rtype: twilio.rest.notify.v1.credential.CredentialContext
"""
return CredentialContext(self._version, sid=sid, )
def __call__(self, sid):
"""
Constructs a CredentialContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.notify.v1.credential.CredentialContext
:rtype: twilio.rest.notify.v1.credential.CredentialContext
"""
return CredentialContext(self._version, sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Notify.V1.CredentialList>'
class CredentialPage(Page):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, response, solution):
"""
Initialize the CredentialPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.notify.v1.credential.CredentialPage
:rtype: twilio.rest.notify.v1.credential.CredentialPage
"""
super(CredentialPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of CredentialInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.notify.v1.credential.CredentialInstance
:rtype: twilio.rest.notify.v1.credential.CredentialInstance
"""
return CredentialInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Notify.V1.CredentialPage>'
class CredentialContext(InstanceContext):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, sid):
"""
Initialize the CredentialContext
:param Version version: Version that contains the resource
:param sid: The unique string that identifies the resource
:returns: twilio.rest.notify.v1.credential.CredentialContext
:rtype: twilio.rest.notify.v1.credential.CredentialContext
"""
super(CredentialContext, self).__init__(version)
# Path Solution
self._solution = {'sid': sid, }
self._uri = '/Credentials/{sid}'.format(**self._solution)
def fetch(self):
"""
Fetch the CredentialInstance
:returns: The fetched CredentialInstance
:rtype: twilio.rest.notify.v1.credential.CredentialInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return CredentialInstance(self._version, payload, sid=self._solution['sid'], )
def update(self, friendly_name=values.unset, certificate=values.unset,
private_key=values.unset, sandbox=values.unset, api_key=values.unset,
secret=values.unset):
"""
Update the CredentialInstance
:param unicode friendly_name: A string to describe the resource
:param unicode certificate: [APN only] The URL-encoded representation of the certificate
:param unicode private_key: [APN only] URL-encoded representation of the private key
:param bool sandbox: [APN only] Whether to send the credential to sandbox APNs
:param unicode api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging
:param unicode secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging
:returns: The updated CredentialInstance
:rtype: twilio.rest.notify.v1.credential.CredentialInstance
"""
data = values.of({
'FriendlyName': friendly_name,
'Certificate': certificate,
'PrivateKey': private_key,
'Sandbox': sandbox,
'ApiKey': api_key,
'Secret': secret,
})
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return CredentialInstance(self._version, payload, sid=self._solution['sid'], )
def delete(self):
"""
Deletes the CredentialInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Notify.V1.CredentialContext {}>'.format(context)
class CredentialInstance(InstanceResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
class PushService(object):
GCM = "gcm"
APN = "apn"
FCM = "fcm"
def __init__(self, version, payload, sid=None):
"""
Initialize the CredentialInstance
:returns: twilio.rest.notify.v1.credential.CredentialInstance
:rtype: twilio.rest.notify.v1.credential.CredentialInstance
"""
super(CredentialInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'account_sid': payload.get('account_sid'),
'friendly_name': payload.get('friendly_name'),
'type': payload.get('type'),
'sandbox': payload.get('sandbox'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: CredentialContext for this CredentialInstance
:rtype: twilio.rest.notify.v1.credential.CredentialContext
"""
if self._context is None:
self._context = CredentialContext(self._version, sid=self._solution['sid'], )
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def friendly_name(self):
"""
:returns: The string that you assigned to describe the resource
:rtype: unicode
"""
return self._properties['friendly_name']
@property
def type(self):
"""
:returns: The Credential type, one of `gcm`, `fcm`, or `apn`
:rtype: CredentialInstance.PushService
"""
return self._properties['type']
@property
def sandbox(self):
"""
:returns: [APN only] Whether to send the credential to sandbox APNs
:rtype: unicode
"""
return self._properties['sandbox']
@property
def date_created(self):
"""
:returns: The RFC 2822 date and time in GMT when the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The RFC 2822 date and time in GMT when the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def url(self):
"""
:returns: The absolute URL of the Credential resource
:rtype: unicode
"""
return self._properties['url']
def fetch(self):
"""
Fetch the CredentialInstance
:returns: The fetched CredentialInstance
:rtype: twilio.rest.notify.v1.credential.CredentialInstance
"""
return self._proxy.fetch()
def update(self, friendly_name=values.unset, certificate=values.unset,
private_key=values.unset, sandbox=values.unset, api_key=values.unset,
secret=values.unset):
"""
Update the CredentialInstance
:param unicode friendly_name: A string to describe the resource
:param unicode certificate: [APN only] The URL-encoded representation of the certificate
:param unicode private_key: [APN only] URL-encoded representation of the private key
:param bool sandbox: [APN only] Whether to send the credential to sandbox APNs
:param unicode api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging
:param unicode secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging
:returns: The updated CredentialInstance
:rtype: twilio.rest.notify.v1.credential.CredentialInstance
"""
return self._proxy.update(
friendly_name=friendly_name,
certificate=certificate,
private_key=private_key,
sandbox=sandbox,
api_key=api_key,
secret=secret,
)
def delete(self):
"""
Deletes the CredentialInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Notify.V1.CredentialInstance {}>'.format(context)
| mit | 204190f93125596758292a8faaa82d99 | 35.364629 | 130 | 0.626539 | 4.478354 | false | false | false | false |
twilio/twilio-python | twilio/rest/messaging/v1/usecase.py | 1 | 3683 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import values
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class UsecaseList(ListResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version):
"""
Initialize the UsecaseList
:param Version version: Version that contains the resource
:returns: twilio.rest.messaging.v1.usecase.UsecaseList
:rtype: twilio.rest.messaging.v1.usecase.UsecaseList
"""
super(UsecaseList, self).__init__(version)
# Path Solution
self._solution = {}
self._uri = '/Services/Usecases'.format(**self._solution)
def fetch(self):
"""
Fetch the UsecaseInstance
:returns: The fetched UsecaseInstance
:rtype: twilio.rest.messaging.v1.usecase.UsecaseInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return UsecaseInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Messaging.V1.UsecaseList>'
class UsecasePage(Page):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, response, solution):
"""
Initialize the UsecasePage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.messaging.v1.usecase.UsecasePage
:rtype: twilio.rest.messaging.v1.usecase.UsecasePage
"""
super(UsecasePage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of UsecaseInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.messaging.v1.usecase.UsecaseInstance
:rtype: twilio.rest.messaging.v1.usecase.UsecaseInstance
"""
return UsecaseInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Messaging.V1.UsecasePage>'
class UsecaseInstance(InstanceResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, payload):
"""
Initialize the UsecaseInstance
:returns: twilio.rest.messaging.v1.usecase.UsecaseInstance
:rtype: twilio.rest.messaging.v1.usecase.UsecaseInstance
"""
super(UsecaseInstance, self).__init__(version)
# Marshaled Properties
self._properties = {'usecases': payload.get('usecases'), }
# Context
self._context = None
self._solution = {}
@property
def usecases(self):
"""
:returns: Human readable Messaging Service Use Case details
:rtype: list[dict]
"""
return self._properties['usecases']
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Messaging.V1.UsecaseInstance>'
| mit | dcb766a140f3e9ae8915ca2c9c0f6b8d | 27.330769 | 78 | 0.621504 | 4.180477 | false | false | false | false |
twilio/twilio-python | twilio/base/domain.py | 3 | 1543 | class Domain(object):
"""
This represents at Twilio API subdomain.
Like, `api.twilio.com` or `lookups.twilio.com'.
"""
def __init__(self, twilio):
"""
:param Twilio twilio:
:return:
"""
self.twilio = twilio
self.base_url = None
def absolute_url(self, uri):
"""
Converts a relative `uri` to an absolute url.
:param string uri: The relative uri to make absolute.
:return: An absolute url (based off this domain)
"""
return '{}/{}'.format(self.base_url.strip('/'), uri.strip('/'))
def request(self, method, uri, params=None, data=None, headers=None,
auth=None, timeout=None, allow_redirects=False):
"""
Makes an HTTP request to this domain.
:param string method: The HTTP method.
:param string uri: The HTTP uri.
:param dict params: Query parameters.
:param object data: The request body.
:param dict headers: The HTTP headers.
:param tuple auth: Basic auth tuple of (username, password)
:param int timeout: The request timeout.
:param bool allow_redirects: True if the client should follow HTTP
redirects.
"""
url = self.absolute_url(uri)
return self.twilio.request(
method,
url,
params=params,
data=data,
headers=headers,
auth=auth,
timeout=timeout,
allow_redirects=allow_redirects
)
| mit | 281338513038572392d498101dfa94c1 | 31.145833 | 74 | 0.562541 | 4.322129 | false | false | false | false |
twilio/twilio-python | twilio/rest/supersim/v1/sim/sim_ip_address.py | 1 | 7833 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import values
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class SimIpAddressList(ListResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, sim_sid):
"""
Initialize the SimIpAddressList
:param Version version: Version that contains the resource
:param sim_sid: The unique string that identifies the resource
:returns: twilio.rest.supersim.v1.sim.sim_ip_address.SimIpAddressList
:rtype: twilio.rest.supersim.v1.sim.sim_ip_address.SimIpAddressList
"""
super(SimIpAddressList, self).__init__(version)
# Path Solution
self._solution = {'sim_sid': sim_sid, }
self._uri = '/Sims/{sim_sid}/IpAddresses'.format(**self._solution)
def stream(self, limit=None, page_size=None):
"""
Streams SimIpAddressInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.supersim.v1.sim.sim_ip_address.SimIpAddressInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, limit=None, page_size=None):
"""
Lists SimIpAddressInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.supersim.v1.sim.sim_ip_address.SimIpAddressInstance]
"""
return list(self.stream(limit=limit, page_size=page_size, ))
def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of SimIpAddressInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of SimIpAddressInstance
:rtype: twilio.rest.supersim.v1.sim.sim_ip_address.SimIpAddressPage
"""
data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })
response = self._version.page(method='GET', uri=self._uri, params=data, )
return SimIpAddressPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of SimIpAddressInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of SimIpAddressInstance
:rtype: twilio.rest.supersim.v1.sim.sim_ip_address.SimIpAddressPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return SimIpAddressPage(self._version, response, self._solution)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Supersim.V1.SimIpAddressList>'
class SimIpAddressPage(Page):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, response, solution):
"""
Initialize the SimIpAddressPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param sim_sid: The unique string that identifies the resource
:returns: twilio.rest.supersim.v1.sim.sim_ip_address.SimIpAddressPage
:rtype: twilio.rest.supersim.v1.sim.sim_ip_address.SimIpAddressPage
"""
super(SimIpAddressPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of SimIpAddressInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.supersim.v1.sim.sim_ip_address.SimIpAddressInstance
:rtype: twilio.rest.supersim.v1.sim.sim_ip_address.SimIpAddressInstance
"""
return SimIpAddressInstance(self._version, payload, sim_sid=self._solution['sim_sid'], )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Supersim.V1.SimIpAddressPage>'
class SimIpAddressInstance(InstanceResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
class IpAddressVersion(object):
IPV4 = "IPv4"
IPV6 = "IPv6"
def __init__(self, version, payload, sim_sid):
"""
Initialize the SimIpAddressInstance
:returns: twilio.rest.supersim.v1.sim.sim_ip_address.SimIpAddressInstance
:rtype: twilio.rest.supersim.v1.sim.sim_ip_address.SimIpAddressInstance
"""
super(SimIpAddressInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'ip_address': payload.get('ip_address'),
'ip_address_version': payload.get('ip_address_version'),
}
# Context
self._context = None
self._solution = {'sim_sid': sim_sid, }
@property
def ip_address(self):
"""
:returns: IP address assigned to the given Super SIM
:rtype: unicode
"""
return self._properties['ip_address']
@property
def ip_address_version(self):
"""
:returns: IP address version
:rtype: SimIpAddressInstance.IpAddressVersion
"""
return self._properties['ip_address_version']
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Supersim.V1.SimIpAddressInstance>'
| mit | 0dd1dc2d32a6c6de240d7f47c9151112 | 35.774648 | 97 | 0.632452 | 4.27799 | false | false | false | false |
twilio/twilio-python | twilio/rest/oauth/v1/oauth.py | 1 | 5379 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class OauthList(ListResource):
def __init__(self, version):
"""
Initialize the OauthList
:param Version version: Version that contains the resource
:returns: twilio.rest.oauth.v1.oauth.OauthList
:rtype: twilio.rest.oauth.v1.oauth.OauthList
"""
super(OauthList, self).__init__(version)
# Path Solution
self._solution = {}
def get(self):
"""
Constructs a OauthContext
:returns: twilio.rest.oauth.v1.oauth.OauthContext
:rtype: twilio.rest.oauth.v1.oauth.OauthContext
"""
return OauthContext(self._version, )
def __call__(self):
"""
Constructs a OauthContext
:returns: twilio.rest.oauth.v1.oauth.OauthContext
:rtype: twilio.rest.oauth.v1.oauth.OauthContext
"""
return OauthContext(self._version, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Oauth.V1.OauthList>'
class OauthPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the OauthPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.oauth.v1.oauth.OauthPage
:rtype: twilio.rest.oauth.v1.oauth.OauthPage
"""
super(OauthPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of OauthInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.oauth.v1.oauth.OauthInstance
:rtype: twilio.rest.oauth.v1.oauth.OauthInstance
"""
return OauthInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Oauth.V1.OauthPage>'
class OauthContext(InstanceContext):
def __init__(self, version):
"""
Initialize the OauthContext
:param Version version: Version that contains the resource
:returns: twilio.rest.oauth.v1.oauth.OauthContext
:rtype: twilio.rest.oauth.v1.oauth.OauthContext
"""
super(OauthContext, self).__init__(version)
# Path Solution
self._solution = {}
self._uri = '/certs'.format(**self._solution)
def fetch(self):
"""
Fetch the OauthInstance
:returns: The fetched OauthInstance
:rtype: twilio.rest.oauth.v1.oauth.OauthInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return OauthInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Oauth.V1.OauthContext {}>'.format(context)
class OauthInstance(InstanceResource):
def __init__(self, version, payload):
"""
Initialize the OauthInstance
:returns: twilio.rest.oauth.v1.oauth.OauthInstance
:rtype: twilio.rest.oauth.v1.oauth.OauthInstance
"""
super(OauthInstance, self).__init__(version)
# Marshaled Properties
self._properties = {'keys': payload.get('keys'), 'url': payload.get('url'), }
# Context
self._context = None
self._solution = {}
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: OauthContext for this OauthInstance
:rtype: twilio.rest.oauth.v1.oauth.OauthContext
"""
if self._context is None:
self._context = OauthContext(self._version, )
return self._context
@property
def keys(self):
"""
:returns: A collection of certificates
:rtype: dict
"""
return self._properties['keys']
@property
def url(self):
"""
:returns: The url
:rtype: unicode
"""
return self._properties['url']
def fetch(self):
"""
Fetch the OauthInstance
:returns: The fetched OauthInstance
:rtype: twilio.rest.oauth.v1.oauth.OauthInstance
"""
return self._proxy.fetch()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Oauth.V1.OauthInstance {}>'.format(context)
| mit | d062404715ea4e971046154678762f40 | 25.761194 | 85 | 0.593605 | 4.062689 | false | false | false | false |
twilio/twilio-python | twilio/rest/trunking/v1/trunk/__init__.py | 1 | 24391 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
from twilio.rest.trunking.v1.trunk.credential_list import CredentialListList
from twilio.rest.trunking.v1.trunk.ip_access_control_list import IpAccessControlListList
from twilio.rest.trunking.v1.trunk.origination_url import OriginationUrlList
from twilio.rest.trunking.v1.trunk.phone_number import PhoneNumberList
from twilio.rest.trunking.v1.trunk.recording import RecordingList
class TrunkList(ListResource):
def __init__(self, version):
"""
Initialize the TrunkList
:param Version version: Version that contains the resource
:returns: twilio.rest.trunking.v1.trunk.TrunkList
:rtype: twilio.rest.trunking.v1.trunk.TrunkList
"""
super(TrunkList, self).__init__(version)
# Path Solution
self._solution = {}
self._uri = '/Trunks'.format(**self._solution)
def create(self, friendly_name=values.unset, domain_name=values.unset,
disaster_recovery_url=values.unset,
disaster_recovery_method=values.unset, transfer_mode=values.unset,
secure=values.unset, cnam_lookup_enabled=values.unset,
transfer_caller_id=values.unset):
"""
Create the TrunkInstance
:param unicode friendly_name: A string to describe the resource
:param unicode domain_name: The unique address you reserve on Twilio to which you route your SIP traffic
:param unicode disaster_recovery_url: The HTTP URL that we should call if an error occurs while sending SIP traffic towards your configured Origination URL
:param unicode disaster_recovery_method: The HTTP method we should use to call the disaster_recovery_url
:param TrunkInstance.TransferSetting transfer_mode: The call transfer settings for the trunk
:param bool secure: Whether Secure Trunking is enabled for the trunk
:param bool cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk
:param TrunkInstance.TransferCallerId transfer_caller_id: Caller Id for transfer target
:returns: The created TrunkInstance
:rtype: twilio.rest.trunking.v1.trunk.TrunkInstance
"""
data = values.of({
'FriendlyName': friendly_name,
'DomainName': domain_name,
'DisasterRecoveryUrl': disaster_recovery_url,
'DisasterRecoveryMethod': disaster_recovery_method,
'TransferMode': transfer_mode,
'Secure': secure,
'CnamLookupEnabled': cnam_lookup_enabled,
'TransferCallerId': transfer_caller_id,
})
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return TrunkInstance(self._version, payload, )
def stream(self, limit=None, page_size=None):
"""
Streams TrunkInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.trunking.v1.trunk.TrunkInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, limit=None, page_size=None):
"""
Lists TrunkInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.trunking.v1.trunk.TrunkInstance]
"""
return list(self.stream(limit=limit, page_size=page_size, ))
def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of TrunkInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of TrunkInstance
:rtype: twilio.rest.trunking.v1.trunk.TrunkPage
"""
data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })
response = self._version.page(method='GET', uri=self._uri, params=data, )
return TrunkPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of TrunkInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of TrunkInstance
:rtype: twilio.rest.trunking.v1.trunk.TrunkPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return TrunkPage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a TrunkContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.trunking.v1.trunk.TrunkContext
:rtype: twilio.rest.trunking.v1.trunk.TrunkContext
"""
return TrunkContext(self._version, sid=sid, )
def __call__(self, sid):
"""
Constructs a TrunkContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.trunking.v1.trunk.TrunkContext
:rtype: twilio.rest.trunking.v1.trunk.TrunkContext
"""
return TrunkContext(self._version, sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Trunking.V1.TrunkList>'
class TrunkPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the TrunkPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.trunking.v1.trunk.TrunkPage
:rtype: twilio.rest.trunking.v1.trunk.TrunkPage
"""
super(TrunkPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of TrunkInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.trunking.v1.trunk.TrunkInstance
:rtype: twilio.rest.trunking.v1.trunk.TrunkInstance
"""
return TrunkInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Trunking.V1.TrunkPage>'
class TrunkContext(InstanceContext):
def __init__(self, version, sid):
"""
Initialize the TrunkContext
:param Version version: Version that contains the resource
:param sid: The unique string that identifies the resource
:returns: twilio.rest.trunking.v1.trunk.TrunkContext
:rtype: twilio.rest.trunking.v1.trunk.TrunkContext
"""
super(TrunkContext, self).__init__(version)
# Path Solution
self._solution = {'sid': sid, }
self._uri = '/Trunks/{sid}'.format(**self._solution)
# Dependents
self._origination_urls = None
self._credentials_lists = None
self._ip_access_control_lists = None
self._phone_numbers = None
self._recordings = None
def fetch(self):
"""
Fetch the TrunkInstance
:returns: The fetched TrunkInstance
:rtype: twilio.rest.trunking.v1.trunk.TrunkInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return TrunkInstance(self._version, payload, sid=self._solution['sid'], )
def delete(self):
"""
Deletes the TrunkInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def update(self, friendly_name=values.unset, domain_name=values.unset,
disaster_recovery_url=values.unset,
disaster_recovery_method=values.unset, transfer_mode=values.unset,
secure=values.unset, cnam_lookup_enabled=values.unset,
transfer_caller_id=values.unset):
"""
Update the TrunkInstance
:param unicode friendly_name: A string to describe the resource
:param unicode domain_name: The unique address you reserve on Twilio to which you route your SIP traffic
:param unicode disaster_recovery_url: The HTTP URL that we should call if an error occurs while sending SIP traffic towards your configured Origination URL
:param unicode disaster_recovery_method: The HTTP method we should use to call the disaster_recovery_url
:param TrunkInstance.TransferSetting transfer_mode: The call transfer settings for the trunk
:param bool secure: Whether Secure Trunking is enabled for the trunk
:param bool cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk
:param TrunkInstance.TransferCallerId transfer_caller_id: Caller Id for transfer target
:returns: The updated TrunkInstance
:rtype: twilio.rest.trunking.v1.trunk.TrunkInstance
"""
data = values.of({
'FriendlyName': friendly_name,
'DomainName': domain_name,
'DisasterRecoveryUrl': disaster_recovery_url,
'DisasterRecoveryMethod': disaster_recovery_method,
'TransferMode': transfer_mode,
'Secure': secure,
'CnamLookupEnabled': cnam_lookup_enabled,
'TransferCallerId': transfer_caller_id,
})
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return TrunkInstance(self._version, payload, sid=self._solution['sid'], )
@property
def origination_urls(self):
"""
Access the origination_urls
:returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList
:rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList
"""
if self._origination_urls is None:
self._origination_urls = OriginationUrlList(self._version, trunk_sid=self._solution['sid'], )
return self._origination_urls
@property
def credentials_lists(self):
"""
Access the credentials_lists
:returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListList
:rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListList
"""
if self._credentials_lists is None:
self._credentials_lists = CredentialListList(self._version, trunk_sid=self._solution['sid'], )
return self._credentials_lists
@property
def ip_access_control_lists(self):
"""
Access the ip_access_control_lists
:returns: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListList
:rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListList
"""
if self._ip_access_control_lists is None:
self._ip_access_control_lists = IpAccessControlListList(
self._version,
trunk_sid=self._solution['sid'],
)
return self._ip_access_control_lists
@property
def phone_numbers(self):
"""
Access the phone_numbers
:returns: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberList
:rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberList
"""
if self._phone_numbers is None:
self._phone_numbers = PhoneNumberList(self._version, trunk_sid=self._solution['sid'], )
return self._phone_numbers
@property
def recordings(self):
"""
Access the recordings
:returns: twilio.rest.trunking.v1.trunk.recording.RecordingList
:rtype: twilio.rest.trunking.v1.trunk.recording.RecordingList
"""
if self._recordings is None:
self._recordings = RecordingList(self._version, trunk_sid=self._solution['sid'], )
return self._recordings
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Trunking.V1.TrunkContext {}>'.format(context)
class TrunkInstance(InstanceResource):
class TransferSetting(object):
DISABLE_ALL = "disable-all"
ENABLE_ALL = "enable-all"
SIP_ONLY = "sip-only"
class TransferCallerId(object):
FROM_TRANSFEREE = "from-transferee"
FROM_TRANSFEROR = "from-transferor"
def __init__(self, version, payload, sid=None):
"""
Initialize the TrunkInstance
:returns: twilio.rest.trunking.v1.trunk.TrunkInstance
:rtype: twilio.rest.trunking.v1.trunk.TrunkInstance
"""
super(TrunkInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'account_sid': payload.get('account_sid'),
'domain_name': payload.get('domain_name'),
'disaster_recovery_method': payload.get('disaster_recovery_method'),
'disaster_recovery_url': payload.get('disaster_recovery_url'),
'friendly_name': payload.get('friendly_name'),
'secure': payload.get('secure'),
'recording': payload.get('recording'),
'transfer_mode': payload.get('transfer_mode'),
'transfer_caller_id': payload.get('transfer_caller_id'),
'cnam_lookup_enabled': payload.get('cnam_lookup_enabled'),
'auth_type': payload.get('auth_type'),
'auth_type_set': payload.get('auth_type_set'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'sid': payload.get('sid'),
'url': payload.get('url'),
'links': payload.get('links'),
}
# Context
self._context = None
self._solution = {'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: TrunkContext for this TrunkInstance
:rtype: twilio.rest.trunking.v1.trunk.TrunkContext
"""
if self._context is None:
self._context = TrunkContext(self._version, sid=self._solution['sid'], )
return self._context
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def domain_name(self):
"""
:returns: The unique address you reserve on Twilio to which you route your SIP traffic
:rtype: unicode
"""
return self._properties['domain_name']
@property
def disaster_recovery_method(self):
"""
:returns: The HTTP method we use to call the disaster_recovery_url
:rtype: unicode
"""
return self._properties['disaster_recovery_method']
@property
def disaster_recovery_url(self):
"""
:returns: The HTTP URL that we call if an error occurs while sending SIP traffic towards your configured Origination URL
:rtype: unicode
"""
return self._properties['disaster_recovery_url']
@property
def friendly_name(self):
"""
:returns: The string that you assigned to describe the resource
:rtype: unicode
"""
return self._properties['friendly_name']
@property
def secure(self):
"""
:returns: Whether Secure Trunking is enabled for the trunk
:rtype: bool
"""
return self._properties['secure']
@property
def recording(self):
"""
:returns: The recording settings for the trunk
:rtype: dict
"""
return self._properties['recording']
@property
def transfer_mode(self):
"""
:returns: The call transfer settings for the trunk
:rtype: TrunkInstance.TransferSetting
"""
return self._properties['transfer_mode']
@property
def transfer_caller_id(self):
"""
:returns: Caller Id for transfer target
:rtype: TrunkInstance.TransferCallerId
"""
return self._properties['transfer_caller_id']
@property
def cnam_lookup_enabled(self):
"""
:returns: Whether Caller ID Name (CNAM) lookup is enabled for the trunk
:rtype: bool
"""
return self._properties['cnam_lookup_enabled']
@property
def auth_type(self):
"""
:returns: The types of authentication mapped to the domain
:rtype: unicode
"""
return self._properties['auth_type']
@property
def auth_type_set(self):
"""
:returns: Reserved
:rtype: list[unicode]
"""
return self._properties['auth_type_set']
@property
def date_created(self):
"""
:returns: The RFC 2822 date and time in GMT when the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The RFC 2822 date and time in GMT when the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def url(self):
"""
:returns: The absolute URL of the resource
:rtype: unicode
"""
return self._properties['url']
@property
def links(self):
"""
:returns: The URLs of related resources
:rtype: unicode
"""
return self._properties['links']
def fetch(self):
"""
Fetch the TrunkInstance
:returns: The fetched TrunkInstance
:rtype: twilio.rest.trunking.v1.trunk.TrunkInstance
"""
return self._proxy.fetch()
def delete(self):
"""
Deletes the TrunkInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def update(self, friendly_name=values.unset, domain_name=values.unset,
disaster_recovery_url=values.unset,
disaster_recovery_method=values.unset, transfer_mode=values.unset,
secure=values.unset, cnam_lookup_enabled=values.unset,
transfer_caller_id=values.unset):
"""
Update the TrunkInstance
:param unicode friendly_name: A string to describe the resource
:param unicode domain_name: The unique address you reserve on Twilio to which you route your SIP traffic
:param unicode disaster_recovery_url: The HTTP URL that we should call if an error occurs while sending SIP traffic towards your configured Origination URL
:param unicode disaster_recovery_method: The HTTP method we should use to call the disaster_recovery_url
:param TrunkInstance.TransferSetting transfer_mode: The call transfer settings for the trunk
:param bool secure: Whether Secure Trunking is enabled for the trunk
:param bool cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk
:param TrunkInstance.TransferCallerId transfer_caller_id: Caller Id for transfer target
:returns: The updated TrunkInstance
:rtype: twilio.rest.trunking.v1.trunk.TrunkInstance
"""
return self._proxy.update(
friendly_name=friendly_name,
domain_name=domain_name,
disaster_recovery_url=disaster_recovery_url,
disaster_recovery_method=disaster_recovery_method,
transfer_mode=transfer_mode,
secure=secure,
cnam_lookup_enabled=cnam_lookup_enabled,
transfer_caller_id=transfer_caller_id,
)
@property
def origination_urls(self):
"""
Access the origination_urls
:returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList
:rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList
"""
return self._proxy.origination_urls
@property
def credentials_lists(self):
"""
Access the credentials_lists
:returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListList
:rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListList
"""
return self._proxy.credentials_lists
@property
def ip_access_control_lists(self):
"""
Access the ip_access_control_lists
:returns: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListList
:rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListList
"""
return self._proxy.ip_access_control_lists
@property
def phone_numbers(self):
"""
Access the phone_numbers
:returns: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberList
:rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberList
"""
return self._proxy.phone_numbers
@property
def recordings(self):
"""
Access the recordings
:returns: twilio.rest.trunking.v1.trunk.recording.RecordingList
:rtype: twilio.rest.trunking.v1.trunk.recording.RecordingList
"""
return self._proxy.recordings
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Trunking.V1.TrunkInstance {}>'.format(context)
| mit | baf1b60abede68a5101c79cdf5cb4180 | 35.081361 | 163 | 0.629863 | 4.186577 | false | false | false | false |
twilio/twilio-python | tests/integration/serverless/v1/service/test_function.py | 1 | 7719 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class FunctionTestCase(IntegrationTestCase):
def test_list_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.functions.list()
self.holodeck.assert_has_request(Request(
'get',
'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions',
))
def test_read_empty_response(self):
self.holodeck.mock(Response(
200,
'''
{
"functions": [],
"meta": {
"first_page_url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions?PageSize=50&Page=0",
"key": "functions",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
"url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions?PageSize=50&Page=0"
}
}
'''
))
actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.functions.list()
self.assertIsNotNone(actual)
def test_fetch_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()
self.holodeck.assert_has_request(Request(
'get',
'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions/ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
))
def test_fetch_response(self):
self.holodeck.mock(Response(
200,
'''
{
"sid": "ZH00000000000000000000000000000000",
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"service_sid": "ZS00000000000000000000000000000000",
"friendly_name": "test-function",
"date_created": "2018-11-10T20:00:00Z",
"date_updated": "2018-11-10T20:00:00Z",
"url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000",
"links": {
"function_versions": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000/Versions"
}
}
'''
))
actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()
self.assertIsNotNone(actual)
def test_delete_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete()
self.holodeck.assert_has_request(Request(
'delete',
'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions/ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
))
def test_delete_response(self):
self.holodeck.mock(Response(
204,
None,
))
actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete()
self.assertTrue(actual)
def test_create_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.functions.create(friendly_name="friendly_name")
values = {'FriendlyName': "friendly_name", }
self.holodeck.assert_has_request(Request(
'post',
'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions',
data=values,
))
def test_create_response(self):
self.holodeck.mock(Response(
201,
'''
{
"sid": "ZH00000000000000000000000000000000",
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"service_sid": "ZS00000000000000000000000000000000",
"friendly_name": "function-friendly",
"date_created": "2018-11-10T20:00:00Z",
"date_updated": "2018-11-10T20:00:00Z",
"url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000",
"links": {
"function_versions": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000/Versions"
}
}
'''
))
actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.functions.create(friendly_name="friendly_name")
self.assertIsNotNone(actual)
def test_update_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(friendly_name="friendly_name")
values = {'FriendlyName': "friendly_name", }
self.holodeck.assert_has_request(Request(
'post',
'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions/ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
data=values,
))
def test_update_response(self):
self.holodeck.mock(Response(
200,
'''
{
"sid": "ZH00000000000000000000000000000000",
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"service_sid": "ZS00000000000000000000000000000000",
"friendly_name": "function-friendly-update",
"date_created": "2018-11-10T20:00:00Z",
"date_updated": "2018-11-10T20:00:00Z",
"url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000",
"links": {
"function_versions": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000/Versions"
}
}
'''
))
actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(friendly_name="friendly_name")
self.assertIsNotNone(actual)
| mit | 1e055618b83c3b6e06722f4b77ca68de | 40.058511 | 173 | 0.591916 | 4.712454 | false | true | false | false |
twilio/twilio-python | tests/integration/pricing/v2/test_country.py | 1 | 5693 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class CountryTestCase(IntegrationTestCase):
def test_list_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.pricing.v2.countries.list()
self.holodeck.assert_has_request(Request(
'get',
'https://pricing.twilio.com/v2/Trunking/Countries',
))
def test_read_full_response(self):
self.holodeck.mock(Response(
200,
'''
{
"countries": [
{
"country": "Andorra",
"iso_country": "AD",
"url": "https://pricing.twilio.com/v2/Trunking/Countries/AD"
}
],
"meta": {
"first_page_url": "https://pricing.twilio.com/v2/Trunking/Countries?PageSize=50&Page=0",
"key": "countries",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
"url": "https://pricing.twilio.com/v2/Trunking/Countries?PageSize=50&Page=0"
}
}
'''
))
actual = self.client.pricing.v2.countries.list()
self.assertIsNotNone(actual)
def test_read_empty_response(self):
self.holodeck.mock(Response(
200,
'''
{
"countries": [],
"meta": {
"first_page_url": "https://pricing.twilio.com/v2/Trunking/Countries?PageSize=50&Page=0",
"key": "countries",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
"url": "https://pricing.twilio.com/v2/Trunking/Countries?PageSize=50&Page=0"
}
}
'''
))
actual = self.client.pricing.v2.countries.list()
self.assertIsNotNone(actual)
def test_fetch_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.pricing.v2.countries("US").fetch()
self.holodeck.assert_has_request(Request(
'get',
'https://pricing.twilio.com/v2/Trunking/Countries/US',
))
def test_fetch_response(self):
self.holodeck.mock(Response(
200,
'''
{
"country": "United States",
"originating_call_prices": [
{
"base_price": null,
"current_price": "0.0085",
"number_type": "local"
},
{
"base_price": null,
"current_price": "0.022",
"number_type": "toll free"
}
],
"iso_country": "US",
"terminating_prefix_prices": [
{
"base_price": null,
"current_price": "0.090",
"destination_prefixes": [
"1907"
],
"friendly_name": "Outbound Trunking Minute - United States - Alaska",
"origination_prefixes": [
"ALL"
]
},
{
"base_price": null,
"current_price": "0.013",
"destination_prefixes": [
"1808"
],
"friendly_name": "Outbound Trunking Minute - United States - Hawaii",
"origination_prefixes": [
"ALL"
]
},
{
"base_price": null,
"current_price": "0.013",
"destination_prefixes": [
"1800",
"1844",
"1855",
"1866",
"1877",
"1888"
],
"friendly_name": "Outbound Trunking Minute - United States & Canada - Toll Free",
"origination_prefixes": [
"ALL"
]
},
{
"base_price": null,
"current_price": "0.013",
"destination_prefixes": [
"1"
],
"friendly_name": "Outbound Trunking Minute - United States & Canada",
"origination_prefixes": [
"ALL"
]
}
],
"price_unit": "USD",
"url": "https://pricing.twilio.com/v2/Trunking/Countries/US"
}
'''
))
actual = self.client.pricing.v2.countries("US").fetch()
self.assertIsNotNone(actual)
| mit | 4dc3a06a1ff23c66c85ab289584e59fe | 32.686391 | 108 | 0.384507 | 4.628455 | false | true | false | false |
twilio/twilio-python | twilio/rest/api/v2010/account/new_key.py | 1 | 5087 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class NewKeyList(ListResource):
def __init__(self, version, account_sid):
"""
Initialize the NewKeyList
:param Version version: Version that contains the resource
:param account_sid: A 34 character string that uniquely identifies this resource.
:returns: twilio.rest.api.v2010.account.new_key.NewKeyList
:rtype: twilio.rest.api.v2010.account.new_key.NewKeyList
"""
super(NewKeyList, self).__init__(version)
# Path Solution
self._solution = {'account_sid': account_sid, }
self._uri = '/Accounts/{account_sid}/Keys.json'.format(**self._solution)
def create(self, friendly_name=values.unset):
"""
Create the NewKeyInstance
:param unicode friendly_name: A string to describe the resource
:returns: The created NewKeyInstance
:rtype: twilio.rest.api.v2010.account.new_key.NewKeyInstance
"""
data = values.of({'FriendlyName': friendly_name, })
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return NewKeyInstance(self._version, payload, account_sid=self._solution['account_sid'], )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Api.V2010.NewKeyList>'
class NewKeyPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the NewKeyPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param account_sid: A 34 character string that uniquely identifies this resource.
:returns: twilio.rest.api.v2010.account.new_key.NewKeyPage
:rtype: twilio.rest.api.v2010.account.new_key.NewKeyPage
"""
super(NewKeyPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of NewKeyInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.new_key.NewKeyInstance
:rtype: twilio.rest.api.v2010.account.new_key.NewKeyInstance
"""
return NewKeyInstance(self._version, payload, account_sid=self._solution['account_sid'], )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Api.V2010.NewKeyPage>'
class NewKeyInstance(InstanceResource):
def __init__(self, version, payload, account_sid):
"""
Initialize the NewKeyInstance
:returns: twilio.rest.api.v2010.account.new_key.NewKeyInstance
:rtype: twilio.rest.api.v2010.account.new_key.NewKeyInstance
"""
super(NewKeyInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'friendly_name': payload.get('friendly_name'),
'date_created': deserialize.rfc2822_datetime(payload.get('date_created')),
'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')),
'secret': payload.get('secret'),
}
# Context
self._context = None
self._solution = {'account_sid': account_sid, }
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def friendly_name(self):
"""
:returns: The string that you assigned to describe the resource
:rtype: unicode
"""
return self._properties['friendly_name']
@property
def date_created(self):
"""
:returns: The RFC 2822 date and time in GMT that the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The RFC 2822 date and time in GMT that the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def secret(self):
"""
:returns: The secret your application uses to sign Access Tokens and to authenticate to the REST API.
:rtype: unicode
"""
return self._properties['secret']
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Api.V2010.NewKeyInstance>'
| mit | de0e0be39aca7c65167b5da06ca710c3 | 29.100592 | 109 | 0.614508 | 4.193735 | false | false | false | false |
twilio/twilio-python | twilio/rest/preview/hosted_numbers/authorization_document/__init__.py | 1 | 20048 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
from twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order import DependentHostedNumberOrderList
class AuthorizationDocumentList(ListResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version):
"""
Initialize the AuthorizationDocumentList
:param Version version: Version that contains the resource
:returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentList
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentList
"""
super(AuthorizationDocumentList, self).__init__(version)
# Path Solution
self._solution = {}
self._uri = '/AuthorizationDocuments'.format(**self._solution)
def stream(self, email=values.unset, status=values.unset, limit=None,
page_size=None):
"""
Streams AuthorizationDocumentInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param unicode email: Email.
:param AuthorizationDocumentInstance.Status status: The Status of this AuthorizationDocument.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(email=email, status=status, page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, email=values.unset, status=values.unset, limit=None,
page_size=None):
"""
Lists AuthorizationDocumentInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param unicode email: Email.
:param AuthorizationDocumentInstance.Status status: The Status of this AuthorizationDocument.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance]
"""
return list(self.stream(email=email, status=status, limit=limit, page_size=page_size, ))
def page(self, email=values.unset, status=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
"""
Retrieve a single page of AuthorizationDocumentInstance records from the API.
Request is executed immediately
:param unicode email: Email.
:param AuthorizationDocumentInstance.Status status: The Status of this AuthorizationDocument.
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of AuthorizationDocumentInstance
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentPage
"""
data = values.of({
'Email': email,
'Status': status,
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(method='GET', uri=self._uri, params=data, )
return AuthorizationDocumentPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of AuthorizationDocumentInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of AuthorizationDocumentInstance
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return AuthorizationDocumentPage(self._version, response, self._solution)
def create(self, hosted_number_order_sids, address_sid, email, contact_title,
contact_phone_number, cc_emails=values.unset):
"""
Create the AuthorizationDocumentInstance
:param list[unicode] hosted_number_order_sids: A list of HostedNumberOrder sids.
:param unicode address_sid: Address sid.
:param unicode email: Email.
:param unicode contact_title: Title of signee of this Authorization Document.
:param unicode contact_phone_number: Authorization Document's signee's phone number.
:param list[unicode] cc_emails: A list of emails.
:returns: The created AuthorizationDocumentInstance
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance
"""
data = values.of({
'HostedNumberOrderSids': serialize.map(hosted_number_order_sids, lambda e: e),
'AddressSid': address_sid,
'Email': email,
'ContactTitle': contact_title,
'ContactPhoneNumber': contact_phone_number,
'CcEmails': serialize.map(cc_emails, lambda e: e),
})
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return AuthorizationDocumentInstance(self._version, payload, )
def get(self, sid):
"""
Constructs a AuthorizationDocumentContext
:param sid: AuthorizationDocument sid.
:returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext
"""
return AuthorizationDocumentContext(self._version, sid=sid, )
def __call__(self, sid):
"""
Constructs a AuthorizationDocumentContext
:param sid: AuthorizationDocument sid.
:returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext
"""
return AuthorizationDocumentContext(self._version, sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Preview.HostedNumbers.AuthorizationDocumentList>'
class AuthorizationDocumentPage(Page):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, response, solution):
"""
Initialize the AuthorizationDocumentPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentPage
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentPage
"""
super(AuthorizationDocumentPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of AuthorizationDocumentInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance
"""
return AuthorizationDocumentInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Preview.HostedNumbers.AuthorizationDocumentPage>'
class AuthorizationDocumentContext(InstanceContext):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, sid):
"""
Initialize the AuthorizationDocumentContext
:param Version version: Version that contains the resource
:param sid: AuthorizationDocument sid.
:returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext
"""
super(AuthorizationDocumentContext, self).__init__(version)
# Path Solution
self._solution = {'sid': sid, }
self._uri = '/AuthorizationDocuments/{sid}'.format(**self._solution)
# Dependents
self._dependent_hosted_number_orders = None
def fetch(self):
"""
Fetch the AuthorizationDocumentInstance
:returns: The fetched AuthorizationDocumentInstance
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return AuthorizationDocumentInstance(self._version, payload, sid=self._solution['sid'], )
def update(self, hosted_number_order_sids=values.unset,
address_sid=values.unset, email=values.unset, cc_emails=values.unset,
status=values.unset, contact_title=values.unset,
contact_phone_number=values.unset):
"""
Update the AuthorizationDocumentInstance
:param list[unicode] hosted_number_order_sids: A list of HostedNumberOrder sids.
:param unicode address_sid: Address sid.
:param unicode email: Email.
:param list[unicode] cc_emails: A list of emails.
:param AuthorizationDocumentInstance.Status status: The Status of this AuthorizationDocument.
:param unicode contact_title: Title of signee of this Authorization Document.
:param unicode contact_phone_number: Authorization Document's signee's phone number.
:returns: The updated AuthorizationDocumentInstance
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance
"""
data = values.of({
'HostedNumberOrderSids': serialize.map(hosted_number_order_sids, lambda e: e),
'AddressSid': address_sid,
'Email': email,
'CcEmails': serialize.map(cc_emails, lambda e: e),
'Status': status,
'ContactTitle': contact_title,
'ContactPhoneNumber': contact_phone_number,
})
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return AuthorizationDocumentInstance(self._version, payload, sid=self._solution['sid'], )
@property
def dependent_hosted_number_orders(self):
"""
Access the dependent_hosted_number_orders
:returns: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderList
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderList
"""
if self._dependent_hosted_number_orders is None:
self._dependent_hosted_number_orders = DependentHostedNumberOrderList(
self._version,
signing_document_sid=self._solution['sid'],
)
return self._dependent_hosted_number_orders
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Preview.HostedNumbers.AuthorizationDocumentContext {}>'.format(context)
class AuthorizationDocumentInstance(InstanceResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
class Status(object):
OPENED = "opened"
SIGNING = "signing"
SIGNED = "signed"
CANCELED = "canceled"
FAILED = "failed"
def __init__(self, version, payload, sid=None):
"""
Initialize the AuthorizationDocumentInstance
:returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance
"""
super(AuthorizationDocumentInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'address_sid': payload.get('address_sid'),
'status': payload.get('status'),
'email': payload.get('email'),
'cc_emails': payload.get('cc_emails'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'url': payload.get('url'),
'links': payload.get('links'),
}
# Context
self._context = None
self._solution = {'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: AuthorizationDocumentContext for this AuthorizationDocumentInstance
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext
"""
if self._context is None:
self._context = AuthorizationDocumentContext(self._version, sid=self._solution['sid'], )
return self._context
@property
def sid(self):
"""
:returns: AuthorizationDocument sid.
:rtype: unicode
"""
return self._properties['sid']
@property
def address_sid(self):
"""
:returns: Address sid.
:rtype: unicode
"""
return self._properties['address_sid']
@property
def status(self):
"""
:returns: The Status of this AuthorizationDocument.
:rtype: AuthorizationDocumentInstance.Status
"""
return self._properties['status']
@property
def email(self):
"""
:returns: Email.
:rtype: unicode
"""
return self._properties['email']
@property
def cc_emails(self):
"""
:returns: A list of emails.
:rtype: list[unicode]
"""
return self._properties['cc_emails']
@property
def date_created(self):
"""
:returns: The date this AuthorizationDocument was created.
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The date this AuthorizationDocument was updated.
:rtype: datetime
"""
return self._properties['date_updated']
@property
def url(self):
"""
:returns: The url
:rtype: unicode
"""
return self._properties['url']
@property
def links(self):
"""
:returns: The links
:rtype: unicode
"""
return self._properties['links']
def fetch(self):
"""
Fetch the AuthorizationDocumentInstance
:returns: The fetched AuthorizationDocumentInstance
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance
"""
return self._proxy.fetch()
def update(self, hosted_number_order_sids=values.unset,
address_sid=values.unset, email=values.unset, cc_emails=values.unset,
status=values.unset, contact_title=values.unset,
contact_phone_number=values.unset):
"""
Update the AuthorizationDocumentInstance
:param list[unicode] hosted_number_order_sids: A list of HostedNumberOrder sids.
:param unicode address_sid: Address sid.
:param unicode email: Email.
:param list[unicode] cc_emails: A list of emails.
:param AuthorizationDocumentInstance.Status status: The Status of this AuthorizationDocument.
:param unicode contact_title: Title of signee of this Authorization Document.
:param unicode contact_phone_number: Authorization Document's signee's phone number.
:returns: The updated AuthorizationDocumentInstance
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance
"""
return self._proxy.update(
hosted_number_order_sids=hosted_number_order_sids,
address_sid=address_sid,
email=email,
cc_emails=cc_emails,
status=status,
contact_title=contact_title,
contact_phone_number=contact_phone_number,
)
@property
def dependent_hosted_number_orders(self):
"""
Access the dependent_hosted_number_orders
:returns: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderList
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderList
"""
return self._proxy.dependent_hosted_number_orders
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Preview.HostedNumbers.AuthorizationDocumentInstance {}>'.format(context)
| mit | c2d39da02a0342166cbe44709c1d11a9 | 38.936255 | 136 | 0.658071 | 4.640741 | false | false | false | false |
twilio/twilio-python | twilio/rest/chat/v2/service/channel/message.py | 1 | 21814 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class MessageList(ListResource):
def __init__(self, version, service_sid, channel_sid):
"""
Initialize the MessageList
:param Version version: Version that contains the resource
:param service_sid: The SID of the Service that the resource is associated with
:param channel_sid: The SID of the Channel the Message resource belongs to
:returns: twilio.rest.chat.v2.service.channel.message.MessageList
:rtype: twilio.rest.chat.v2.service.channel.message.MessageList
"""
super(MessageList, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, 'channel_sid': channel_sid, }
self._uri = '/Services/{service_sid}/Channels/{channel_sid}/Messages'.format(**self._solution)
def create(self, from_=values.unset, attributes=values.unset,
date_created=values.unset, date_updated=values.unset,
last_updated_by=values.unset, body=values.unset,
media_sid=values.unset, x_twilio_webhook_enabled=values.unset):
"""
Create the MessageInstance
:param unicode from_: The Identity of the new message's author
:param unicode attributes: A valid JSON string that contains application-specific data
:param datetime date_created: The ISO 8601 date and time in GMT when the resource was created
:param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated
:param unicode last_updated_by: The Identity of the User who last updated the Message
:param unicode body: The message to send to the channel
:param unicode media_sid: The Media Sid to be attached to the new Message
:param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header
:returns: The created MessageInstance
:rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance
"""
data = values.of({
'From': from_,
'Attributes': attributes,
'DateCreated': serialize.iso8601_datetime(date_created),
'DateUpdated': serialize.iso8601_datetime(date_updated),
'LastUpdatedBy': last_updated_by,
'Body': body,
'MediaSid': media_sid,
})
headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, })
payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, )
return MessageInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
channel_sid=self._solution['channel_sid'],
)
def stream(self, order=values.unset, limit=None, page_size=None):
"""
Streams MessageInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param MessageInstance.OrderType order: The sort order of the returned messages
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.chat.v2.service.channel.message.MessageInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(order=order, page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, order=values.unset, limit=None, page_size=None):
"""
Lists MessageInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param MessageInstance.OrderType order: The sort order of the returned messages
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.chat.v2.service.channel.message.MessageInstance]
"""
return list(self.stream(order=order, limit=limit, page_size=page_size, ))
def page(self, order=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
"""
Retrieve a single page of MessageInstance records from the API.
Request is executed immediately
:param MessageInstance.OrderType order: The sort order of the returned messages
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of MessageInstance
:rtype: twilio.rest.chat.v2.service.channel.message.MessagePage
"""
data = values.of({
'Order': order,
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(method='GET', uri=self._uri, params=data, )
return MessagePage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of MessageInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of MessageInstance
:rtype: twilio.rest.chat.v2.service.channel.message.MessagePage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return MessagePage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a MessageContext
:param sid: The SID of the Message resource to fetch
:returns: twilio.rest.chat.v2.service.channel.message.MessageContext
:rtype: twilio.rest.chat.v2.service.channel.message.MessageContext
"""
return MessageContext(
self._version,
service_sid=self._solution['service_sid'],
channel_sid=self._solution['channel_sid'],
sid=sid,
)
def __call__(self, sid):
"""
Constructs a MessageContext
:param sid: The SID of the Message resource to fetch
:returns: twilio.rest.chat.v2.service.channel.message.MessageContext
:rtype: twilio.rest.chat.v2.service.channel.message.MessageContext
"""
return MessageContext(
self._version,
service_sid=self._solution['service_sid'],
channel_sid=self._solution['channel_sid'],
sid=sid,
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Chat.V2.MessageList>'
class MessagePage(Page):
def __init__(self, version, response, solution):
"""
Initialize the MessagePage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param service_sid: The SID of the Service that the resource is associated with
:param channel_sid: The SID of the Channel the Message resource belongs to
:returns: twilio.rest.chat.v2.service.channel.message.MessagePage
:rtype: twilio.rest.chat.v2.service.channel.message.MessagePage
"""
super(MessagePage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of MessageInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.chat.v2.service.channel.message.MessageInstance
:rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance
"""
return MessageInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
channel_sid=self._solution['channel_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Chat.V2.MessagePage>'
class MessageContext(InstanceContext):
def __init__(self, version, service_sid, channel_sid, sid):
"""
Initialize the MessageContext
:param Version version: Version that contains the resource
:param service_sid: The SID of the Service to fetch the resource from
:param channel_sid: The SID of the Channel the message to fetch belongs to
:param sid: The SID of the Message resource to fetch
:returns: twilio.rest.chat.v2.service.channel.message.MessageContext
:rtype: twilio.rest.chat.v2.service.channel.message.MessageContext
"""
super(MessageContext, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, 'channel_sid': channel_sid, 'sid': sid, }
self._uri = '/Services/{service_sid}/Channels/{channel_sid}/Messages/{sid}'.format(**self._solution)
def fetch(self):
"""
Fetch the MessageInstance
:returns: The fetched MessageInstance
:rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return MessageInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
channel_sid=self._solution['channel_sid'],
sid=self._solution['sid'],
)
def delete(self, x_twilio_webhook_enabled=values.unset):
"""
Deletes the MessageInstance
:param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, })
return self._version.delete(method='DELETE', uri=self._uri, headers=headers, )
def update(self, body=values.unset, attributes=values.unset,
date_created=values.unset, date_updated=values.unset,
last_updated_by=values.unset, from_=values.unset,
x_twilio_webhook_enabled=values.unset):
"""
Update the MessageInstance
:param unicode body: The message to send to the channel
:param unicode attributes: A valid JSON string that contains application-specific data
:param datetime date_created: The ISO 8601 date and time in GMT when the resource was created
:param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated
:param unicode last_updated_by: The Identity of the User who last updated the Message, if applicable
:param unicode from_: The Identity of the message's author
:param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header
:returns: The updated MessageInstance
:rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance
"""
data = values.of({
'Body': body,
'Attributes': attributes,
'DateCreated': serialize.iso8601_datetime(date_created),
'DateUpdated': serialize.iso8601_datetime(date_updated),
'LastUpdatedBy': last_updated_by,
'From': from_,
})
headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, })
payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, )
return MessageInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
channel_sid=self._solution['channel_sid'],
sid=self._solution['sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Chat.V2.MessageContext {}>'.format(context)
class MessageInstance(InstanceResource):
class OrderType(object):
ASC = "asc"
DESC = "desc"
class WebhookEnabledType(object):
TRUE = "true"
FALSE = "false"
def __init__(self, version, payload, service_sid, channel_sid, sid=None):
"""
Initialize the MessageInstance
:returns: twilio.rest.chat.v2.service.channel.message.MessageInstance
:rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance
"""
super(MessageInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'account_sid': payload.get('account_sid'),
'attributes': payload.get('attributes'),
'service_sid': payload.get('service_sid'),
'to': payload.get('to'),
'channel_sid': payload.get('channel_sid'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'last_updated_by': payload.get('last_updated_by'),
'was_edited': payload.get('was_edited'),
'from_': payload.get('from'),
'body': payload.get('body'),
'index': deserialize.integer(payload.get('index')),
'type': payload.get('type'),
'media': payload.get('media'),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {
'service_sid': service_sid,
'channel_sid': channel_sid,
'sid': sid or self._properties['sid'],
}
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: MessageContext for this MessageInstance
:rtype: twilio.rest.chat.v2.service.channel.message.MessageContext
"""
if self._context is None:
self._context = MessageContext(
self._version,
service_sid=self._solution['service_sid'],
channel_sid=self._solution['channel_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def attributes(self):
"""
:returns: The JSON string that stores application-specific data
:rtype: unicode
"""
return self._properties['attributes']
@property
def service_sid(self):
"""
:returns: The SID of the Service that the resource is associated with
:rtype: unicode
"""
return self._properties['service_sid']
@property
def to(self):
"""
:returns: The SID of the Channel that the message was sent to
:rtype: unicode
"""
return self._properties['to']
@property
def channel_sid(self):
"""
:returns: The SID of the Channel the Message resource belongs to
:rtype: unicode
"""
return self._properties['channel_sid']
@property
def date_created(self):
"""
:returns: The RFC 2822 date and time in GMT when the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The RFC 2822 date and time in GMT when the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def last_updated_by(self):
"""
:returns: The Identity of the User who last updated the Message
:rtype: unicode
"""
return self._properties['last_updated_by']
@property
def was_edited(self):
"""
:returns: Whether the message has been edited since it was created
:rtype: bool
"""
return self._properties['was_edited']
@property
def from_(self):
"""
:returns: The Identity of the message's author
:rtype: unicode
"""
return self._properties['from_']
@property
def body(self):
"""
:returns: The content of the message
:rtype: unicode
"""
return self._properties['body']
@property
def index(self):
"""
:returns: The index of the message within the Channel
:rtype: unicode
"""
return self._properties['index']
@property
def type(self):
"""
:returns: The Message type
:rtype: unicode
"""
return self._properties['type']
@property
def media(self):
"""
:returns: A Media object that describes the Message's media if attached; otherwise, null
:rtype: dict
"""
return self._properties['media']
@property
def url(self):
"""
:returns: The absolute URL of the Message resource
:rtype: unicode
"""
return self._properties['url']
def fetch(self):
"""
Fetch the MessageInstance
:returns: The fetched MessageInstance
:rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance
"""
return self._proxy.fetch()
def delete(self, x_twilio_webhook_enabled=values.unset):
"""
Deletes the MessageInstance
:param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled, )
def update(self, body=values.unset, attributes=values.unset,
date_created=values.unset, date_updated=values.unset,
last_updated_by=values.unset, from_=values.unset,
x_twilio_webhook_enabled=values.unset):
"""
Update the MessageInstance
:param unicode body: The message to send to the channel
:param unicode attributes: A valid JSON string that contains application-specific data
:param datetime date_created: The ISO 8601 date and time in GMT when the resource was created
:param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated
:param unicode last_updated_by: The Identity of the User who last updated the Message, if applicable
:param unicode from_: The Identity of the message's author
:param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header
:returns: The updated MessageInstance
:rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance
"""
return self._proxy.update(
body=body,
attributes=attributes,
date_created=date_created,
date_updated=date_updated,
last_updated_by=last_updated_by,
from_=from_,
x_twilio_webhook_enabled=x_twilio_webhook_enabled,
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Chat.V2.MessageInstance {}>'.format(context)
| mit | c9d2fd90dfda69b21385e16d7c36a34f | 35.600671 | 124 | 0.615385 | 4.387369 | false | false | false | false |
twilio/twilio-python | twilio/rest/api/v2010/account/available_phone_number/local.py | 1 | 20361 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class LocalList(ListResource):
def __init__(self, version, account_sid, country_code):
"""
Initialize the LocalList
:param Version version: Version that contains the resource
:param account_sid: The account_sid
:param country_code: The ISO-3166-1 country code of the country.
:returns: twilio.rest.api.v2010.account.available_phone_number.local.LocalList
:rtype: twilio.rest.api.v2010.account.available_phone_number.local.LocalList
"""
super(LocalList, self).__init__(version)
# Path Solution
self._solution = {'account_sid': account_sid, 'country_code': country_code, }
self._uri = '/Accounts/{account_sid}/AvailablePhoneNumbers/{country_code}/Local.json'.format(**self._solution)
def stream(self, area_code=values.unset, contains=values.unset,
sms_enabled=values.unset, mms_enabled=values.unset,
voice_enabled=values.unset,
exclude_all_address_required=values.unset,
exclude_local_address_required=values.unset,
exclude_foreign_address_required=values.unset, beta=values.unset,
near_number=values.unset, near_lat_long=values.unset,
distance=values.unset, in_postal_code=values.unset,
in_region=values.unset, in_rate_center=values.unset,
in_lata=values.unset, in_locality=values.unset,
fax_enabled=values.unset, limit=None, page_size=None):
"""
Streams LocalInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param unicode area_code: The area code of the phone numbers to read
:param unicode contains: The pattern on which to match phone numbers
:param bool sms_enabled: Whether the phone numbers can receive text messages
:param bool mms_enabled: Whether the phone numbers can receive MMS messages
:param bool voice_enabled: Whether the phone numbers can receive calls.
:param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address
:param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address
:param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address
:param bool beta: Whether to read phone numbers new to the Twilio platform
:param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only)
:param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only)
:param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only)
:param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only)
:param unicode in_region: Limit results to a particular region. (US/Canada only)
:param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only)
:param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only)
:param unicode in_locality: Limit results to a particular locality
:param bool fax_enabled: Whether the phone numbers can receive faxes
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.api.v2010.account.available_phone_number.local.LocalInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(
area_code=area_code,
contains=contains,
sms_enabled=sms_enabled,
mms_enabled=mms_enabled,
voice_enabled=voice_enabled,
exclude_all_address_required=exclude_all_address_required,
exclude_local_address_required=exclude_local_address_required,
exclude_foreign_address_required=exclude_foreign_address_required,
beta=beta,
near_number=near_number,
near_lat_long=near_lat_long,
distance=distance,
in_postal_code=in_postal_code,
in_region=in_region,
in_rate_center=in_rate_center,
in_lata=in_lata,
in_locality=in_locality,
fax_enabled=fax_enabled,
page_size=limits['page_size'],
)
return self._version.stream(page, limits['limit'])
def list(self, area_code=values.unset, contains=values.unset,
sms_enabled=values.unset, mms_enabled=values.unset,
voice_enabled=values.unset, exclude_all_address_required=values.unset,
exclude_local_address_required=values.unset,
exclude_foreign_address_required=values.unset, beta=values.unset,
near_number=values.unset, near_lat_long=values.unset,
distance=values.unset, in_postal_code=values.unset,
in_region=values.unset, in_rate_center=values.unset,
in_lata=values.unset, in_locality=values.unset,
fax_enabled=values.unset, limit=None, page_size=None):
"""
Lists LocalInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param unicode area_code: The area code of the phone numbers to read
:param unicode contains: The pattern on which to match phone numbers
:param bool sms_enabled: Whether the phone numbers can receive text messages
:param bool mms_enabled: Whether the phone numbers can receive MMS messages
:param bool voice_enabled: Whether the phone numbers can receive calls.
:param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address
:param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address
:param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address
:param bool beta: Whether to read phone numbers new to the Twilio platform
:param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only)
:param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only)
:param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only)
:param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only)
:param unicode in_region: Limit results to a particular region. (US/Canada only)
:param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only)
:param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only)
:param unicode in_locality: Limit results to a particular locality
:param bool fax_enabled: Whether the phone numbers can receive faxes
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.api.v2010.account.available_phone_number.local.LocalInstance]
"""
return list(self.stream(
area_code=area_code,
contains=contains,
sms_enabled=sms_enabled,
mms_enabled=mms_enabled,
voice_enabled=voice_enabled,
exclude_all_address_required=exclude_all_address_required,
exclude_local_address_required=exclude_local_address_required,
exclude_foreign_address_required=exclude_foreign_address_required,
beta=beta,
near_number=near_number,
near_lat_long=near_lat_long,
distance=distance,
in_postal_code=in_postal_code,
in_region=in_region,
in_rate_center=in_rate_center,
in_lata=in_lata,
in_locality=in_locality,
fax_enabled=fax_enabled,
limit=limit,
page_size=page_size,
))
def page(self, area_code=values.unset, contains=values.unset,
sms_enabled=values.unset, mms_enabled=values.unset,
voice_enabled=values.unset, exclude_all_address_required=values.unset,
exclude_local_address_required=values.unset,
exclude_foreign_address_required=values.unset, beta=values.unset,
near_number=values.unset, near_lat_long=values.unset,
distance=values.unset, in_postal_code=values.unset,
in_region=values.unset, in_rate_center=values.unset,
in_lata=values.unset, in_locality=values.unset,
fax_enabled=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
"""
Retrieve a single page of LocalInstance records from the API.
Request is executed immediately
:param unicode area_code: The area code of the phone numbers to read
:param unicode contains: The pattern on which to match phone numbers
:param bool sms_enabled: Whether the phone numbers can receive text messages
:param bool mms_enabled: Whether the phone numbers can receive MMS messages
:param bool voice_enabled: Whether the phone numbers can receive calls.
:param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address
:param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address
:param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address
:param bool beta: Whether to read phone numbers new to the Twilio platform
:param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only)
:param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only)
:param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only)
:param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only)
:param unicode in_region: Limit results to a particular region. (US/Canada only)
:param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only)
:param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only)
:param unicode in_locality: Limit results to a particular locality
:param bool fax_enabled: Whether the phone numbers can receive faxes
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of LocalInstance
:rtype: twilio.rest.api.v2010.account.available_phone_number.local.LocalPage
"""
data = values.of({
'AreaCode': area_code,
'Contains': contains,
'SmsEnabled': sms_enabled,
'MmsEnabled': mms_enabled,
'VoiceEnabled': voice_enabled,
'ExcludeAllAddressRequired': exclude_all_address_required,
'ExcludeLocalAddressRequired': exclude_local_address_required,
'ExcludeForeignAddressRequired': exclude_foreign_address_required,
'Beta': beta,
'NearNumber': near_number,
'NearLatLong': near_lat_long,
'Distance': distance,
'InPostalCode': in_postal_code,
'InRegion': in_region,
'InRateCenter': in_rate_center,
'InLata': in_lata,
'InLocality': in_locality,
'FaxEnabled': fax_enabled,
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(method='GET', uri=self._uri, params=data, )
return LocalPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of LocalInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of LocalInstance
:rtype: twilio.rest.api.v2010.account.available_phone_number.local.LocalPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return LocalPage(self._version, response, self._solution)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Api.V2010.LocalList>'
class LocalPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the LocalPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param account_sid: The account_sid
:param country_code: The ISO-3166-1 country code of the country.
:returns: twilio.rest.api.v2010.account.available_phone_number.local.LocalPage
:rtype: twilio.rest.api.v2010.account.available_phone_number.local.LocalPage
"""
super(LocalPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of LocalInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.available_phone_number.local.LocalInstance
:rtype: twilio.rest.api.v2010.account.available_phone_number.local.LocalInstance
"""
return LocalInstance(
self._version,
payload,
account_sid=self._solution['account_sid'],
country_code=self._solution['country_code'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Api.V2010.LocalPage>'
class LocalInstance(InstanceResource):
def __init__(self, version, payload, account_sid, country_code):
"""
Initialize the LocalInstance
:returns: twilio.rest.api.v2010.account.available_phone_number.local.LocalInstance
:rtype: twilio.rest.api.v2010.account.available_phone_number.local.LocalInstance
"""
super(LocalInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'friendly_name': payload.get('friendly_name'),
'phone_number': payload.get('phone_number'),
'lata': payload.get('lata'),
'locality': payload.get('locality'),
'rate_center': payload.get('rate_center'),
'latitude': deserialize.decimal(payload.get('latitude')),
'longitude': deserialize.decimal(payload.get('longitude')),
'region': payload.get('region'),
'postal_code': payload.get('postal_code'),
'iso_country': payload.get('iso_country'),
'address_requirements': payload.get('address_requirements'),
'beta': payload.get('beta'),
'capabilities': payload.get('capabilities'),
}
# Context
self._context = None
self._solution = {'account_sid': account_sid, 'country_code': country_code, }
@property
def friendly_name(self):
"""
:returns: A formatted version of the phone number
:rtype: unicode
"""
return self._properties['friendly_name']
@property
def phone_number(self):
"""
:returns: The phone number in E.164 format
:rtype: unicode
"""
return self._properties['phone_number']
@property
def lata(self):
"""
:returns: The LATA of this phone number
:rtype: unicode
"""
return self._properties['lata']
@property
def locality(self):
"""
:returns: The locality or city of this phone number's location
:rtype: unicode
"""
return self._properties['locality']
@property
def rate_center(self):
"""
:returns: The rate center of this phone number
:rtype: unicode
"""
return self._properties['rate_center']
@property
def latitude(self):
"""
:returns: The latitude of this phone number's location
:rtype: unicode
"""
return self._properties['latitude']
@property
def longitude(self):
"""
:returns: The longitude of this phone number's location
:rtype: unicode
"""
return self._properties['longitude']
@property
def region(self):
"""
:returns: The two-letter state or province abbreviation of this phone number's location
:rtype: unicode
"""
return self._properties['region']
@property
def postal_code(self):
"""
:returns: The postal or ZIP code of this phone number's location
:rtype: unicode
"""
return self._properties['postal_code']
@property
def iso_country(self):
"""
:returns: The ISO country code of this phone number
:rtype: unicode
"""
return self._properties['iso_country']
@property
def address_requirements(self):
"""
:returns: The type of Address resource the phone number requires
:rtype: unicode
"""
return self._properties['address_requirements']
@property
def beta(self):
"""
:returns: Whether the phone number is new to the Twilio platform
:rtype: bool
"""
return self._properties['beta']
@property
def capabilities(self):
"""
:returns: Whether a phone number can receive calls or messages
:rtype: unicode
"""
return self._properties['capabilities']
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Api.V2010.LocalInstance>'
| mit | 2e5d5d7ca45960cfe80f9f1483647ccf | 43.749451 | 171 | 0.640784 | 4.32293 | false | false | false | false |
twilio/twilio-python | twilio/rest/proxy/v1/service/session/participant/__init__.py | 1 | 18213 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
from twilio.rest.proxy.v1.service.session.participant.message_interaction import MessageInteractionList
class ParticipantList(ListResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, service_sid, session_sid):
"""
Initialize the ParticipantList
:param Version version: Version that contains the resource
:param service_sid: The SID of the resource's parent Service
:param session_sid: The SID of the resource's parent Session
:returns: twilio.rest.proxy.v1.service.session.participant.ParticipantList
:rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantList
"""
super(ParticipantList, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, 'session_sid': session_sid, }
self._uri = '/Services/{service_sid}/Sessions/{session_sid}/Participants'.format(**self._solution)
def stream(self, limit=None, page_size=None):
"""
Streams ParticipantInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.proxy.v1.service.session.participant.ParticipantInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, limit=None, page_size=None):
"""
Lists ParticipantInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.proxy.v1.service.session.participant.ParticipantInstance]
"""
return list(self.stream(limit=limit, page_size=page_size, ))
def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of ParticipantInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of ParticipantInstance
:rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantPage
"""
data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })
response = self._version.page(method='GET', uri=self._uri, params=data, )
return ParticipantPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of ParticipantInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of ParticipantInstance
:rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return ParticipantPage(self._version, response, self._solution)
def create(self, identifier, friendly_name=values.unset,
proxy_identifier=values.unset, proxy_identifier_sid=values.unset):
"""
Create the ParticipantInstance
:param unicode identifier: The phone number of the Participant
:param unicode friendly_name: The string that you assigned to describe the participant
:param unicode proxy_identifier: The proxy phone number to use for the Participant
:param unicode proxy_identifier_sid: The Proxy Identifier Sid
:returns: The created ParticipantInstance
:rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance
"""
data = values.of({
'Identifier': identifier,
'FriendlyName': friendly_name,
'ProxyIdentifier': proxy_identifier,
'ProxyIdentifierSid': proxy_identifier_sid,
})
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return ParticipantInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
session_sid=self._solution['session_sid'],
)
def get(self, sid):
"""
Constructs a ParticipantContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.proxy.v1.service.session.participant.ParticipantContext
:rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantContext
"""
return ParticipantContext(
self._version,
service_sid=self._solution['service_sid'],
session_sid=self._solution['session_sid'],
sid=sid,
)
def __call__(self, sid):
"""
Constructs a ParticipantContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.proxy.v1.service.session.participant.ParticipantContext
:rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantContext
"""
return ParticipantContext(
self._version,
service_sid=self._solution['service_sid'],
session_sid=self._solution['session_sid'],
sid=sid,
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Proxy.V1.ParticipantList>'
class ParticipantPage(Page):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, response, solution):
"""
Initialize the ParticipantPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param service_sid: The SID of the resource's parent Service
:param session_sid: The SID of the resource's parent Session
:returns: twilio.rest.proxy.v1.service.session.participant.ParticipantPage
:rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantPage
"""
super(ParticipantPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of ParticipantInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance
:rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance
"""
return ParticipantInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
session_sid=self._solution['session_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Proxy.V1.ParticipantPage>'
class ParticipantContext(InstanceContext):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, service_sid, session_sid, sid):
"""
Initialize the ParticipantContext
:param Version version: Version that contains the resource
:param service_sid: The SID of the parent Service of the resource to fetch
:param session_sid: The SID of the parent Session of the resource to fetch
:param sid: The unique string that identifies the resource
:returns: twilio.rest.proxy.v1.service.session.participant.ParticipantContext
:rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantContext
"""
super(ParticipantContext, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, 'session_sid': session_sid, 'sid': sid, }
self._uri = '/Services/{service_sid}/Sessions/{session_sid}/Participants/{sid}'.format(**self._solution)
# Dependents
self._message_interactions = None
def fetch(self):
"""
Fetch the ParticipantInstance
:returns: The fetched ParticipantInstance
:rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return ParticipantInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
session_sid=self._solution['session_sid'],
sid=self._solution['sid'],
)
def delete(self):
"""
Deletes the ParticipantInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
@property
def message_interactions(self):
"""
Access the message_interactions
:returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList
:rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList
"""
if self._message_interactions is None:
self._message_interactions = MessageInteractionList(
self._version,
service_sid=self._solution['service_sid'],
session_sid=self._solution['session_sid'],
participant_sid=self._solution['sid'],
)
return self._message_interactions
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Proxy.V1.ParticipantContext {}>'.format(context)
class ParticipantInstance(InstanceResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, payload, service_sid, session_sid, sid=None):
"""
Initialize the ParticipantInstance
:returns: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance
:rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance
"""
super(ParticipantInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'session_sid': payload.get('session_sid'),
'service_sid': payload.get('service_sid'),
'account_sid': payload.get('account_sid'),
'friendly_name': payload.get('friendly_name'),
'identifier': payload.get('identifier'),
'proxy_identifier': payload.get('proxy_identifier'),
'proxy_identifier_sid': payload.get('proxy_identifier_sid'),
'date_deleted': deserialize.iso8601_datetime(payload.get('date_deleted')),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'url': payload.get('url'),
'links': payload.get('links'),
}
# Context
self._context = None
self._solution = {
'service_sid': service_sid,
'session_sid': session_sid,
'sid': sid or self._properties['sid'],
}
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ParticipantContext for this ParticipantInstance
:rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantContext
"""
if self._context is None:
self._context = ParticipantContext(
self._version,
service_sid=self._solution['service_sid'],
session_sid=self._solution['session_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def session_sid(self):
"""
:returns: The SID of the resource's parent Session
:rtype: unicode
"""
return self._properties['session_sid']
@property
def service_sid(self):
"""
:returns: The SID of the resource's parent Service
:rtype: unicode
"""
return self._properties['service_sid']
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def friendly_name(self):
"""
:returns: The string that you assigned to describe the participant
:rtype: unicode
"""
return self._properties['friendly_name']
@property
def identifier(self):
"""
:returns: The phone number or channel identifier of the Participant
:rtype: unicode
"""
return self._properties['identifier']
@property
def proxy_identifier(self):
"""
:returns: The phone number or short code of the participant's partner
:rtype: unicode
"""
return self._properties['proxy_identifier']
@property
def proxy_identifier_sid(self):
"""
:returns: The SID of the Proxy Identifier assigned to the Participant
:rtype: unicode
"""
return self._properties['proxy_identifier_sid']
@property
def date_deleted(self):
"""
:returns: The ISO 8601 date the Participant was removed
:rtype: datetime
"""
return self._properties['date_deleted']
@property
def date_created(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def url(self):
"""
:returns: The absolute URL of the Participant resource
:rtype: unicode
"""
return self._properties['url']
@property
def links(self):
"""
:returns: The URLs to resources related the participant
:rtype: unicode
"""
return self._properties['links']
def fetch(self):
"""
Fetch the ParticipantInstance
:returns: The fetched ParticipantInstance
:rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance
"""
return self._proxy.fetch()
def delete(self):
"""
Deletes the ParticipantInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
@property
def message_interactions(self):
"""
Access the message_interactions
:returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList
:rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList
"""
return self._proxy.message_interactions
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Proxy.V1.ParticipantInstance {}>'.format(context)
| mit | d9d85e51fd383f372121e82b4e3e3da3 | 34.781925 | 112 | 0.622797 | 4.485961 | false | false | false | false |
twilio/twilio-python | twilio/rest/conversations/v1/role.py | 1 | 13583 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class RoleList(ListResource):
def __init__(self, version):
"""
Initialize the RoleList
:param Version version: Version that contains the resource
:returns: twilio.rest.conversations.v1.role.RoleList
:rtype: twilio.rest.conversations.v1.role.RoleList
"""
super(RoleList, self).__init__(version)
# Path Solution
self._solution = {}
self._uri = '/Roles'.format(**self._solution)
def create(self, friendly_name, type, permission):
"""
Create the RoleInstance
:param unicode friendly_name: A string to describe the new resource
:param RoleInstance.RoleType type: The type of role
:param list[unicode] permission: A permission the role should have
:returns: The created RoleInstance
:rtype: twilio.rest.conversations.v1.role.RoleInstance
"""
data = values.of({
'FriendlyName': friendly_name,
'Type': type,
'Permission': serialize.map(permission, lambda e: e),
})
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return RoleInstance(self._version, payload, )
def stream(self, limit=None, page_size=None):
"""
Streams RoleInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.conversations.v1.role.RoleInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, limit=None, page_size=None):
"""
Lists RoleInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.conversations.v1.role.RoleInstance]
"""
return list(self.stream(limit=limit, page_size=page_size, ))
def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of RoleInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of RoleInstance
:rtype: twilio.rest.conversations.v1.role.RolePage
"""
data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })
response = self._version.page(method='GET', uri=self._uri, params=data, )
return RolePage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of RoleInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of RoleInstance
:rtype: twilio.rest.conversations.v1.role.RolePage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return RolePage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a RoleContext
:param sid: The SID of the Role resource to fetch
:returns: twilio.rest.conversations.v1.role.RoleContext
:rtype: twilio.rest.conversations.v1.role.RoleContext
"""
return RoleContext(self._version, sid=sid, )
def __call__(self, sid):
"""
Constructs a RoleContext
:param sid: The SID of the Role resource to fetch
:returns: twilio.rest.conversations.v1.role.RoleContext
:rtype: twilio.rest.conversations.v1.role.RoleContext
"""
return RoleContext(self._version, sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Conversations.V1.RoleList>'
class RolePage(Page):
def __init__(self, version, response, solution):
"""
Initialize the RolePage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.conversations.v1.role.RolePage
:rtype: twilio.rest.conversations.v1.role.RolePage
"""
super(RolePage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of RoleInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.conversations.v1.role.RoleInstance
:rtype: twilio.rest.conversations.v1.role.RoleInstance
"""
return RoleInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Conversations.V1.RolePage>'
class RoleContext(InstanceContext):
def __init__(self, version, sid):
"""
Initialize the RoleContext
:param Version version: Version that contains the resource
:param sid: The SID of the Role resource to fetch
:returns: twilio.rest.conversations.v1.role.RoleContext
:rtype: twilio.rest.conversations.v1.role.RoleContext
"""
super(RoleContext, self).__init__(version)
# Path Solution
self._solution = {'sid': sid, }
self._uri = '/Roles/{sid}'.format(**self._solution)
def update(self, permission):
"""
Update the RoleInstance
:param list[unicode] permission: A permission the role should have
:returns: The updated RoleInstance
:rtype: twilio.rest.conversations.v1.role.RoleInstance
"""
data = values.of({'Permission': serialize.map(permission, lambda e: e), })
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return RoleInstance(self._version, payload, sid=self._solution['sid'], )
def delete(self):
"""
Deletes the RoleInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def fetch(self):
"""
Fetch the RoleInstance
:returns: The fetched RoleInstance
:rtype: twilio.rest.conversations.v1.role.RoleInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return RoleInstance(self._version, payload, sid=self._solution['sid'], )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Conversations.V1.RoleContext {}>'.format(context)
class RoleInstance(InstanceResource):
class RoleType(object):
CONVERSATION = "conversation"
SERVICE = "service"
def __init__(self, version, payload, sid=None):
"""
Initialize the RoleInstance
:returns: twilio.rest.conversations.v1.role.RoleInstance
:rtype: twilio.rest.conversations.v1.role.RoleInstance
"""
super(RoleInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'account_sid': payload.get('account_sid'),
'chat_service_sid': payload.get('chat_service_sid'),
'friendly_name': payload.get('friendly_name'),
'type': payload.get('type'),
'permissions': payload.get('permissions'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: RoleContext for this RoleInstance
:rtype: twilio.rest.conversations.v1.role.RoleContext
"""
if self._context is None:
self._context = RoleContext(self._version, sid=self._solution['sid'], )
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def chat_service_sid(self):
"""
:returns: The SID of the Conversation Service that the resource is associated with
:rtype: unicode
"""
return self._properties['chat_service_sid']
@property
def friendly_name(self):
"""
:returns: The string that you assigned to describe the resource
:rtype: unicode
"""
return self._properties['friendly_name']
@property
def type(self):
"""
:returns: The type of role
:rtype: RoleInstance.RoleType
"""
return self._properties['type']
@property
def permissions(self):
"""
:returns: An array of the permissions the role has been granted
:rtype: list[unicode]
"""
return self._properties['permissions']
@property
def date_created(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def url(self):
"""
:returns: An absolute URL for this user role.
:rtype: unicode
"""
return self._properties['url']
def update(self, permission):
"""
Update the RoleInstance
:param list[unicode] permission: A permission the role should have
:returns: The updated RoleInstance
:rtype: twilio.rest.conversations.v1.role.RoleInstance
"""
return self._proxy.update(permission, )
def delete(self):
"""
Deletes the RoleInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def fetch(self):
"""
Fetch the RoleInstance
:returns: The fetched RoleInstance
:rtype: twilio.rest.conversations.v1.role.RoleInstance
"""
return self._proxy.fetch()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Conversations.V1.RoleInstance {}>'.format(context)
| mit | 638488e6d8c51bb08ba251d3794010d2 | 31.263658 | 97 | 0.606714 | 4.320293 | false | false | false | false |
twilio/twilio-python | tests/integration/voice/v1/dialing_permissions/test_bulk_country_update.py | 2 | 1308 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class BulkCountryUpdateTestCase(IntegrationTestCase):
def test_create_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.voice.v1.dialing_permissions \
.bulk_country_updates.create(update_request="update_request")
values = {'UpdateRequest': "update_request", }
self.holodeck.assert_has_request(Request(
'post',
'https://voice.twilio.com/v1/DialingPermissions/BulkCountryUpdates',
data=values,
))
def test_create_response(self):
self.holodeck.mock(Response(
201,
'''
{
"update_count": 1,
"update_request": "accepted"
}
'''
))
actual = self.client.voice.v1.dialing_permissions \
.bulk_country_updates.create(update_request="update_request")
self.assertIsNotNone(actual)
| mit | bdb63eecb34dacd7ad7b373a8bd956bf | 27.434783 | 98 | 0.566514 | 3.987805 | false | true | false | false |
twilio/twilio-python | tests/integration/api/v2010/account/recording/test_transcription.py | 1 | 7373 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class TranscriptionTestCase(IntegrationTestCase):
def test_fetch_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.transcriptions("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()
self.holodeck.assert_has_request(Request(
'get',
'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Transcriptions/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json',
))
def test_fetch_response(self):
self.holodeck.mock(Response(
200,
'''
{
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"api_version": "2008-08-01",
"date_created": "Mon, 22 Aug 2011 20:58:44 +0000",
"date_updated": "Mon, 22 Aug 2011 20:58:44 +0000",
"duration": "10",
"price": "0.00000",
"price_unit": "USD",
"recording_sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"status": "in-progress",
"transcription_text": "THIS IS A TEST",
"type": "fast",
"uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json"
}
'''
))
actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.transcriptions("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()
self.assertIsNotNone(actual)
def test_delete_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.transcriptions("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete()
self.holodeck.assert_has_request(Request(
'delete',
'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Transcriptions/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json',
))
def test_delete_response(self):
self.holodeck.mock(Response(
204,
None,
))
actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.transcriptions("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete()
self.assertTrue(actual)
def test_list_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.transcriptions.list()
self.holodeck.assert_has_request(Request(
'get',
'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Transcriptions.json',
))
def test_read_full_response(self):
self.holodeck.mock(Response(
200,
'''
{
"end": 0,
"first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=50&Page=0",
"last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=50&Page=0",
"next_page_uri": null,
"num_pages": 1,
"page": 0,
"page_size": 50,
"previous_page_uri": null,
"start": 0,
"total": 1,
"transcriptions": [
{
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"api_version": "2008-08-01",
"date_created": "Mon, 22 Aug 2011 20:58:44 +0000",
"date_updated": "Mon, 22 Aug 2011 20:58:44 +0000",
"duration": "10",
"price": "0.00000",
"price_unit": "USD",
"recording_sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"status": "in-progress",
"transcription_text": "THIS IS A TEST",
"type": "fast",
"uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json"
}
],
"uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=50&Page=0"
}
'''
))
actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.transcriptions.list()
self.assertIsNotNone(actual)
def test_read_empty_response(self):
self.holodeck.mock(Response(
200,
'''
{
"end": 0,
"first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=50&Page=0",
"last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=50&Page=0",
"next_page_uri": null,
"num_pages": 1,
"page": 0,
"page_size": 50,
"previous_page_uri": null,
"start": 0,
"total": 1,
"transcriptions": [],
"uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=50&Page=0"
}
'''
))
actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.transcriptions.list()
self.assertIsNotNone(actual)
| mit | d0526be050db056f787f323bb83eaed8 | 43.957317 | 193 | 0.566527 | 4.750644 | false | true | false | false |
twilio/twilio-python | tests/integration/media/v1/test_media_recording.py | 1 | 6383 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class MediaRecordingTestCase(IntegrationTestCase):
def test_delete_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.media.v1.media_recording("KVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete()
self.holodeck.assert_has_request(Request(
'delete',
'https://media.twilio.com/v1/MediaRecordings/KVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
))
def test_delete_response(self):
self.holodeck.mock(Response(
204,
None,
))
actual = self.client.media.v1.media_recording("KVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete()
self.assertTrue(actual)
def test_fetch_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.media.v1.media_recording("KVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()
self.holodeck.assert_has_request(Request(
'get',
'https://media.twilio.com/v1/MediaRecordings/KVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
))
def test_fetch_response(self):
self.holodeck.mock(Response(
200,
'''
{
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"date_created": "2015-07-30T20:00:00Z",
"date_updated": "2015-07-30T20:00:00Z",
"duration": 2147483647,
"format": "mp4",
"links": {
"media": "https://media.twilio.com/v1/MediaRecordings/KVcafebabecafebabecafebabecafebabe/Media",
"timed_metadata": "https://media.twilio.com/v1/MediaRecordings/KVcafebabecafebabecafebabecafebabe/TimedMetadata"
},
"processor_sid": "ZXcafebabecafebabecafebabecafebabe",
"resolution": "640x480",
"source_sid": "RMcafebabecafebabecafebabecafebabe",
"sid": "KVcafebabecafebabecafebabecafebabe",
"media_size": 2147483648,
"status": "completed",
"status_callback": "https://www.example.com",
"status_callback_method": "POST",
"url": "https://media.twilio.com/v1/MediaRecordings/KVcafebabecafebabecafebabecafebabe"
}
'''
))
actual = self.client.media.v1.media_recording("KVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()
self.assertIsNotNone(actual)
def test_list_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.media.v1.media_recording.list()
self.holodeck.assert_has_request(Request(
'get',
'https://media.twilio.com/v1/MediaRecordings',
))
def test_read_empty_response(self):
self.holodeck.mock(Response(
200,
'''
{
"meta": {
"page": 0,
"page_size": 10,
"first_page_url": "https://media.twilio.com/v1/MediaRecordings?Status=processing&SourceSid=RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&ProcessorSid=ZXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Order=asc&PageSize=10&Page=0",
"previous_page_url": null,
"url": "https://media.twilio.com/v1/MediaRecordings?Status=processing&SourceSid=RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&ProcessorSid=ZXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Order=asc&PageSize=10&Page=0",
"next_page_url": null,
"key": "media_recordings"
},
"media_recordings": []
}
'''
))
actual = self.client.media.v1.media_recording.list()
self.assertIsNotNone(actual)
def test_read_items_response(self):
self.holodeck.mock(Response(
200,
'''
{
"meta": {
"page": 0,
"page_size": 10,
"first_page_url": "https://media.twilio.com/v1/MediaRecordings?Status=completed&SourceSid=RMcafebabecafebabecafebabecafebabe&ProcessorSid=ZXcafebabecafebabecafebabecafebabe&Order=desc&PageSize=10&Page=0",
"previous_page_url": null,
"url": "https://media.twilio.com/v1/MediaRecordings?Status=completed&SourceSid=RMcafebabecafebabecafebabecafebabe&ProcessorSid=ZXcafebabecafebabecafebabecafebabe&Order=desc&PageSize=10&Page=0",
"next_page_url": null,
"key": "media_recordings"
},
"media_recordings": [
{
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"date_created": "2015-07-30T20:00:00Z",
"date_updated": "2015-07-30T20:00:00Z",
"duration": 1000,
"format": "mp4",
"links": {
"media": "https://media.twilio.com/v1/MediaRecordings/KVcafebabecafebabecafebabecafebabe/Media",
"timed_metadata": "https://media.twilio.com/v1/MediaRecordings/KVcafebabecafebabecafebabecafebabe/TimedMetadata"
},
"processor_sid": "ZXcafebabecafebabecafebabecafebabe",
"resolution": "640x480",
"source_sid": "RMcafebabecafebabecafebabecafebabe",
"sid": "KVcafebabecafebabecafebabecafebabe",
"media_size": 1000,
"status": "completed",
"status_callback": "https://www.example.com",
"status_callback_method": "POST",
"url": "https://media.twilio.com/v1/MediaRecordings/KVcafebabecafebabecafebabecafebabe"
}
]
}
'''
))
actual = self.client.media.v1.media_recording.list()
self.assertIsNotNone(actual)
| mit | d281ca2733fd3a6421491cda6461a648 | 39.916667 | 224 | 0.559141 | 3.942557 | false | true | false | false |
twilio/twilio-python | twilio/rest/chat/v1/credential.py | 1 | 16191 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class CredentialList(ListResource):
def __init__(self, version):
"""
Initialize the CredentialList
:param Version version: Version that contains the resource
:returns: twilio.rest.chat.v1.credential.CredentialList
:rtype: twilio.rest.chat.v1.credential.CredentialList
"""
super(CredentialList, self).__init__(version)
# Path Solution
self._solution = {}
self._uri = '/Credentials'.format(**self._solution)
def stream(self, limit=None, page_size=None):
"""
Streams CredentialInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.chat.v1.credential.CredentialInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, limit=None, page_size=None):
"""
Lists CredentialInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.chat.v1.credential.CredentialInstance]
"""
return list(self.stream(limit=limit, page_size=page_size, ))
def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of CredentialInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of CredentialInstance
:rtype: twilio.rest.chat.v1.credential.CredentialPage
"""
data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })
response = self._version.page(method='GET', uri=self._uri, params=data, )
return CredentialPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of CredentialInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of CredentialInstance
:rtype: twilio.rest.chat.v1.credential.CredentialPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return CredentialPage(self._version, response, self._solution)
def create(self, type, friendly_name=values.unset, certificate=values.unset,
private_key=values.unset, sandbox=values.unset, api_key=values.unset,
secret=values.unset):
"""
Create the CredentialInstance
:param CredentialInstance.PushService type: The type of push-notification service the credential is for
:param unicode friendly_name: A string to describe the resource
:param unicode certificate: [APN only] The URL encoded representation of the certificate
:param unicode private_key: [APN only] The URL encoded representation of the private key
:param bool sandbox: [APN only] Whether to send the credential to sandbox APNs
:param unicode api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential
:param unicode secret: [FCM only] The Server key of your project from Firebase console
:returns: The created CredentialInstance
:rtype: twilio.rest.chat.v1.credential.CredentialInstance
"""
data = values.of({
'Type': type,
'FriendlyName': friendly_name,
'Certificate': certificate,
'PrivateKey': private_key,
'Sandbox': sandbox,
'ApiKey': api_key,
'Secret': secret,
})
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return CredentialInstance(self._version, payload, )
def get(self, sid):
"""
Constructs a CredentialContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.chat.v1.credential.CredentialContext
:rtype: twilio.rest.chat.v1.credential.CredentialContext
"""
return CredentialContext(self._version, sid=sid, )
def __call__(self, sid):
"""
Constructs a CredentialContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.chat.v1.credential.CredentialContext
:rtype: twilio.rest.chat.v1.credential.CredentialContext
"""
return CredentialContext(self._version, sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Chat.V1.CredentialList>'
class CredentialPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the CredentialPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.chat.v1.credential.CredentialPage
:rtype: twilio.rest.chat.v1.credential.CredentialPage
"""
super(CredentialPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of CredentialInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.chat.v1.credential.CredentialInstance
:rtype: twilio.rest.chat.v1.credential.CredentialInstance
"""
return CredentialInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Chat.V1.CredentialPage>'
class CredentialContext(InstanceContext):
def __init__(self, version, sid):
"""
Initialize the CredentialContext
:param Version version: Version that contains the resource
:param sid: The unique string that identifies the resource
:returns: twilio.rest.chat.v1.credential.CredentialContext
:rtype: twilio.rest.chat.v1.credential.CredentialContext
"""
super(CredentialContext, self).__init__(version)
# Path Solution
self._solution = {'sid': sid, }
self._uri = '/Credentials/{sid}'.format(**self._solution)
def fetch(self):
"""
Fetch the CredentialInstance
:returns: The fetched CredentialInstance
:rtype: twilio.rest.chat.v1.credential.CredentialInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return CredentialInstance(self._version, payload, sid=self._solution['sid'], )
def update(self, friendly_name=values.unset, certificate=values.unset,
private_key=values.unset, sandbox=values.unset, api_key=values.unset,
secret=values.unset):
"""
Update the CredentialInstance
:param unicode friendly_name: A string to describe the resource
:param unicode certificate: [APN only] The URL encoded representation of the certificate
:param unicode private_key: [APN only] The URL encoded representation of the private key
:param bool sandbox: [APN only] Whether to send the credential to sandbox APNs
:param unicode api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential
:param unicode secret: [FCM only] The Server key of your project from Firebase console
:returns: The updated CredentialInstance
:rtype: twilio.rest.chat.v1.credential.CredentialInstance
"""
data = values.of({
'FriendlyName': friendly_name,
'Certificate': certificate,
'PrivateKey': private_key,
'Sandbox': sandbox,
'ApiKey': api_key,
'Secret': secret,
})
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return CredentialInstance(self._version, payload, sid=self._solution['sid'], )
def delete(self):
"""
Deletes the CredentialInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Chat.V1.CredentialContext {}>'.format(context)
class CredentialInstance(InstanceResource):
class PushService(object):
GCM = "gcm"
APN = "apn"
FCM = "fcm"
def __init__(self, version, payload, sid=None):
"""
Initialize the CredentialInstance
:returns: twilio.rest.chat.v1.credential.CredentialInstance
:rtype: twilio.rest.chat.v1.credential.CredentialInstance
"""
super(CredentialInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'account_sid': payload.get('account_sid'),
'friendly_name': payload.get('friendly_name'),
'type': payload.get('type'),
'sandbox': payload.get('sandbox'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: CredentialContext for this CredentialInstance
:rtype: twilio.rest.chat.v1.credential.CredentialContext
"""
if self._context is None:
self._context = CredentialContext(self._version, sid=self._solution['sid'], )
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def friendly_name(self):
"""
:returns: The string that you assigned to describe the resource
:rtype: unicode
"""
return self._properties['friendly_name']
@property
def type(self):
"""
:returns: The type of push-notification service the credential is for
:rtype: CredentialInstance.PushService
"""
return self._properties['type']
@property
def sandbox(self):
"""
:returns: [APN only] Whether to send the credential to sandbox APNs
:rtype: unicode
"""
return self._properties['sandbox']
@property
def date_created(self):
"""
:returns: The RFC 2822 date and time in GMT when the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The RFC 2822 date and time in GMT when the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def url(self):
"""
:returns: The absolute URL of the Credential resource
:rtype: unicode
"""
return self._properties['url']
def fetch(self):
"""
Fetch the CredentialInstance
:returns: The fetched CredentialInstance
:rtype: twilio.rest.chat.v1.credential.CredentialInstance
"""
return self._proxy.fetch()
def update(self, friendly_name=values.unset, certificate=values.unset,
private_key=values.unset, sandbox=values.unset, api_key=values.unset,
secret=values.unset):
"""
Update the CredentialInstance
:param unicode friendly_name: A string to describe the resource
:param unicode certificate: [APN only] The URL encoded representation of the certificate
:param unicode private_key: [APN only] The URL encoded representation of the private key
:param bool sandbox: [APN only] Whether to send the credential to sandbox APNs
:param unicode api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential
:param unicode secret: [FCM only] The Server key of your project from Firebase console
:returns: The updated CredentialInstance
:rtype: twilio.rest.chat.v1.credential.CredentialInstance
"""
return self._proxy.update(
friendly_name=friendly_name,
certificate=certificate,
private_key=private_key,
sandbox=sandbox,
api_key=api_key,
secret=secret,
)
def delete(self):
"""
Deletes the CredentialInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Chat.V1.CredentialInstance {}>'.format(context)
| mit | f887de2581760c58dd2b9701b19e9f27 | 34.98 | 166 | 0.625286 | 4.491262 | false | false | false | false |
twilio/twilio-python | twilio/rest/ip_messaging/v1/service/channel/__init__.py | 1 | 19213 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
from twilio.rest.ip_messaging.v1.service.channel.invite import InviteList
from twilio.rest.ip_messaging.v1.service.channel.member import MemberList
from twilio.rest.ip_messaging.v1.service.channel.message import MessageList
class ChannelList(ListResource):
def __init__(self, version, service_sid):
"""
Initialize the ChannelList
:param Version version: Version that contains the resource
:param service_sid: The service_sid
:returns: twilio.rest.ip_messaging.v1.service.channel.ChannelList
:rtype: twilio.rest.ip_messaging.v1.service.channel.ChannelList
"""
super(ChannelList, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, }
self._uri = '/Services/{service_sid}/Channels'.format(**self._solution)
def create(self, friendly_name=values.unset, unique_name=values.unset,
attributes=values.unset, type=values.unset):
"""
Create the ChannelInstance
:param unicode friendly_name: The friendly_name
:param unicode unique_name: The unique_name
:param unicode attributes: The attributes
:param ChannelInstance.ChannelType type: The type
:returns: The created ChannelInstance
:rtype: twilio.rest.ip_messaging.v1.service.channel.ChannelInstance
"""
data = values.of({
'FriendlyName': friendly_name,
'UniqueName': unique_name,
'Attributes': attributes,
'Type': type,
})
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], )
def stream(self, type=values.unset, limit=None, page_size=None):
"""
Streams ChannelInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param list[ChannelInstance.ChannelType] type: The type
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.ip_messaging.v1.service.channel.ChannelInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(type=type, page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, type=values.unset, limit=None, page_size=None):
"""
Lists ChannelInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param list[ChannelInstance.ChannelType] type: The type
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.ip_messaging.v1.service.channel.ChannelInstance]
"""
return list(self.stream(type=type, limit=limit, page_size=page_size, ))
def page(self, type=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
"""
Retrieve a single page of ChannelInstance records from the API.
Request is executed immediately
:param list[ChannelInstance.ChannelType] type: The type
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of ChannelInstance
:rtype: twilio.rest.ip_messaging.v1.service.channel.ChannelPage
"""
data = values.of({
'Type': serialize.map(type, lambda e: e),
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(method='GET', uri=self._uri, params=data, )
return ChannelPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of ChannelInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of ChannelInstance
:rtype: twilio.rest.ip_messaging.v1.service.channel.ChannelPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return ChannelPage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a ChannelContext
:param sid: The sid
:returns: twilio.rest.ip_messaging.v1.service.channel.ChannelContext
:rtype: twilio.rest.ip_messaging.v1.service.channel.ChannelContext
"""
return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, )
def __call__(self, sid):
"""
Constructs a ChannelContext
:param sid: The sid
:returns: twilio.rest.ip_messaging.v1.service.channel.ChannelContext
:rtype: twilio.rest.ip_messaging.v1.service.channel.ChannelContext
"""
return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.IpMessaging.V1.ChannelList>'
class ChannelPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the ChannelPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param service_sid: The service_sid
:returns: twilio.rest.ip_messaging.v1.service.channel.ChannelPage
:rtype: twilio.rest.ip_messaging.v1.service.channel.ChannelPage
"""
super(ChannelPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of ChannelInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.ip_messaging.v1.service.channel.ChannelInstance
:rtype: twilio.rest.ip_messaging.v1.service.channel.ChannelInstance
"""
return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.IpMessaging.V1.ChannelPage>'
class ChannelContext(InstanceContext):
def __init__(self, version, service_sid, sid):
"""
Initialize the ChannelContext
:param Version version: Version that contains the resource
:param service_sid: The service_sid
:param sid: The sid
:returns: twilio.rest.ip_messaging.v1.service.channel.ChannelContext
:rtype: twilio.rest.ip_messaging.v1.service.channel.ChannelContext
"""
super(ChannelContext, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, 'sid': sid, }
self._uri = '/Services/{service_sid}/Channels/{sid}'.format(**self._solution)
# Dependents
self._members = None
self._messages = None
self._invites = None
def fetch(self):
"""
Fetch the ChannelInstance
:returns: The fetched ChannelInstance
:rtype: twilio.rest.ip_messaging.v1.service.channel.ChannelInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return ChannelInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
sid=self._solution['sid'],
)
def delete(self):
"""
Deletes the ChannelInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def update(self, friendly_name=values.unset, unique_name=values.unset,
attributes=values.unset):
"""
Update the ChannelInstance
:param unicode friendly_name: The friendly_name
:param unicode unique_name: The unique_name
:param unicode attributes: The attributes
:returns: The updated ChannelInstance
:rtype: twilio.rest.ip_messaging.v1.service.channel.ChannelInstance
"""
data = values.of({
'FriendlyName': friendly_name,
'UniqueName': unique_name,
'Attributes': attributes,
})
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return ChannelInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
sid=self._solution['sid'],
)
@property
def members(self):
"""
Access the members
:returns: twilio.rest.ip_messaging.v1.service.channel.member.MemberList
:rtype: twilio.rest.ip_messaging.v1.service.channel.member.MemberList
"""
if self._members is None:
self._members = MemberList(
self._version,
service_sid=self._solution['service_sid'],
channel_sid=self._solution['sid'],
)
return self._members
@property
def messages(self):
"""
Access the messages
:returns: twilio.rest.ip_messaging.v1.service.channel.message.MessageList
:rtype: twilio.rest.ip_messaging.v1.service.channel.message.MessageList
"""
if self._messages is None:
self._messages = MessageList(
self._version,
service_sid=self._solution['service_sid'],
channel_sid=self._solution['sid'],
)
return self._messages
@property
def invites(self):
"""
Access the invites
:returns: twilio.rest.ip_messaging.v1.service.channel.invite.InviteList
:rtype: twilio.rest.ip_messaging.v1.service.channel.invite.InviteList
"""
if self._invites is None:
self._invites = InviteList(
self._version,
service_sid=self._solution['service_sid'],
channel_sid=self._solution['sid'],
)
return self._invites
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.IpMessaging.V1.ChannelContext {}>'.format(context)
class ChannelInstance(InstanceResource):
class ChannelType(object):
PUBLIC = "public"
PRIVATE = "private"
def __init__(self, version, payload, service_sid, sid=None):
"""
Initialize the ChannelInstance
:returns: twilio.rest.ip_messaging.v1.service.channel.ChannelInstance
:rtype: twilio.rest.ip_messaging.v1.service.channel.ChannelInstance
"""
super(ChannelInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'account_sid': payload.get('account_sid'),
'service_sid': payload.get('service_sid'),
'friendly_name': payload.get('friendly_name'),
'unique_name': payload.get('unique_name'),
'attributes': payload.get('attributes'),
'type': payload.get('type'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'created_by': payload.get('created_by'),
'members_count': deserialize.integer(payload.get('members_count')),
'messages_count': deserialize.integer(payload.get('messages_count')),
'url': payload.get('url'),
'links': payload.get('links'),
}
# Context
self._context = None
self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ChannelContext for this ChannelInstance
:rtype: twilio.rest.ip_messaging.v1.service.channel.ChannelContext
"""
if self._context is None:
self._context = ChannelContext(
self._version,
service_sid=self._solution['service_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def sid(self):
"""
:returns: The sid
:rtype: unicode
"""
return self._properties['sid']
@property
def account_sid(self):
"""
:returns: The account_sid
:rtype: unicode
"""
return self._properties['account_sid']
@property
def service_sid(self):
"""
:returns: The service_sid
:rtype: unicode
"""
return self._properties['service_sid']
@property
def friendly_name(self):
"""
:returns: The friendly_name
:rtype: unicode
"""
return self._properties['friendly_name']
@property
def unique_name(self):
"""
:returns: The unique_name
:rtype: unicode
"""
return self._properties['unique_name']
@property
def attributes(self):
"""
:returns: The attributes
:rtype: unicode
"""
return self._properties['attributes']
@property
def type(self):
"""
:returns: The type
:rtype: ChannelInstance.ChannelType
"""
return self._properties['type']
@property
def date_created(self):
"""
:returns: The date_created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The date_updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def created_by(self):
"""
:returns: The created_by
:rtype: unicode
"""
return self._properties['created_by']
@property
def members_count(self):
"""
:returns: The members_count
:rtype: unicode
"""
return self._properties['members_count']
@property
def messages_count(self):
"""
:returns: The messages_count
:rtype: unicode
"""
return self._properties['messages_count']
@property
def url(self):
"""
:returns: The url
:rtype: unicode
"""
return self._properties['url']
@property
def links(self):
"""
:returns: The links
:rtype: unicode
"""
return self._properties['links']
def fetch(self):
"""
Fetch the ChannelInstance
:returns: The fetched ChannelInstance
:rtype: twilio.rest.ip_messaging.v1.service.channel.ChannelInstance
"""
return self._proxy.fetch()
def delete(self):
"""
Deletes the ChannelInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def update(self, friendly_name=values.unset, unique_name=values.unset,
attributes=values.unset):
"""
Update the ChannelInstance
:param unicode friendly_name: The friendly_name
:param unicode unique_name: The unique_name
:param unicode attributes: The attributes
:returns: The updated ChannelInstance
:rtype: twilio.rest.ip_messaging.v1.service.channel.ChannelInstance
"""
return self._proxy.update(
friendly_name=friendly_name,
unique_name=unique_name,
attributes=attributes,
)
@property
def members(self):
"""
Access the members
:returns: twilio.rest.ip_messaging.v1.service.channel.member.MemberList
:rtype: twilio.rest.ip_messaging.v1.service.channel.member.MemberList
"""
return self._proxy.members
@property
def messages(self):
"""
Access the messages
:returns: twilio.rest.ip_messaging.v1.service.channel.message.MessageList
:rtype: twilio.rest.ip_messaging.v1.service.channel.message.MessageList
"""
return self._proxy.messages
@property
def invites(self):
"""
Access the invites
:returns: twilio.rest.ip_messaging.v1.service.channel.invite.InviteList
:rtype: twilio.rest.ip_messaging.v1.service.channel.invite.InviteList
"""
return self._proxy.invites
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.IpMessaging.V1.ChannelInstance {}>'.format(context)
| mit | fc8d164bd9e32c6202727eb7d3c40497 | 31.345118 | 99 | 0.600739 | 4.327252 | false | false | false | false |
twilio/twilio-python | twilio/rest/autopilot/v1/assistant/task/sample.py | 1 | 18390 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class SampleList(ListResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, assistant_sid, task_sid):
"""
Initialize the SampleList
:param Version version: Version that contains the resource
:param assistant_sid: The SID of the Assistant that is the parent of the Task associated with the resource
:param task_sid: The SID of the Task associated with the resource
:returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleList
:rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleList
"""
super(SampleList, self).__init__(version)
# Path Solution
self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, }
self._uri = '/Assistants/{assistant_sid}/Tasks/{task_sid}/Samples'.format(**self._solution)
def stream(self, language=values.unset, limit=None, page_size=None):
"""
Streams SampleInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param unicode language: The ISO language-country string that specifies the language used for the sample
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(language=language, page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, language=values.unset, limit=None, page_size=None):
"""
Lists SampleInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param unicode language: The ISO language-country string that specifies the language used for the sample
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance]
"""
return list(self.stream(language=language, limit=limit, page_size=page_size, ))
def page(self, language=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
"""
Retrieve a single page of SampleInstance records from the API.
Request is executed immediately
:param unicode language: The ISO language-country string that specifies the language used for the sample
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of SampleInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.sample.SamplePage
"""
data = values.of({
'Language': language,
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(method='GET', uri=self._uri, params=data, )
return SamplePage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of SampleInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of SampleInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.sample.SamplePage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return SamplePage(self._version, response, self._solution)
def create(self, language, tagged_text, source_channel=values.unset):
"""
Create the SampleInstance
:param unicode language: The ISO language-country string that specifies the language used for the new sample
:param unicode tagged_text: The text example of how end users might express the task
:param unicode source_channel: The communication channel from which the new sample was captured
:returns: The created SampleInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance
"""
data = values.of({'Language': language, 'TaggedText': tagged_text, 'SourceChannel': source_channel, })
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return SampleInstance(
self._version,
payload,
assistant_sid=self._solution['assistant_sid'],
task_sid=self._solution['task_sid'],
)
def get(self, sid):
"""
Constructs a SampleContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleContext
:rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleContext
"""
return SampleContext(
self._version,
assistant_sid=self._solution['assistant_sid'],
task_sid=self._solution['task_sid'],
sid=sid,
)
def __call__(self, sid):
"""
Constructs a SampleContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleContext
:rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleContext
"""
return SampleContext(
self._version,
assistant_sid=self._solution['assistant_sid'],
task_sid=self._solution['task_sid'],
sid=sid,
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Autopilot.V1.SampleList>'
class SamplePage(Page):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, response, solution):
"""
Initialize the SamplePage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param assistant_sid: The SID of the Assistant that is the parent of the Task associated with the resource
:param task_sid: The SID of the Task associated with the resource
:returns: twilio.rest.autopilot.v1.assistant.task.sample.SamplePage
:rtype: twilio.rest.autopilot.v1.assistant.task.sample.SamplePage
"""
super(SamplePage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of SampleInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance
"""
return SampleInstance(
self._version,
payload,
assistant_sid=self._solution['assistant_sid'],
task_sid=self._solution['task_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Autopilot.V1.SamplePage>'
class SampleContext(InstanceContext):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, assistant_sid, task_sid, sid):
"""
Initialize the SampleContext
:param Version version: Version that contains the resource
:param assistant_sid: The SID of the Assistant that is the parent of the Task associated with the resource to fetch
:param task_sid: The SID of the Task associated with the Sample resource to create
:param sid: The unique string that identifies the resource
:returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleContext
:rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleContext
"""
super(SampleContext, self).__init__(version)
# Path Solution
self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, 'sid': sid, }
self._uri = '/Assistants/{assistant_sid}/Tasks/{task_sid}/Samples/{sid}'.format(**self._solution)
def fetch(self):
"""
Fetch the SampleInstance
:returns: The fetched SampleInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return SampleInstance(
self._version,
payload,
assistant_sid=self._solution['assistant_sid'],
task_sid=self._solution['task_sid'],
sid=self._solution['sid'],
)
def update(self, language=values.unset, tagged_text=values.unset,
source_channel=values.unset):
"""
Update the SampleInstance
:param unicode language: The ISO language-country string that specifies the language used for the sample
:param unicode tagged_text: The text example of how end users might express the task
:param unicode source_channel: The communication channel from which the sample was captured
:returns: The updated SampleInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance
"""
data = values.of({'Language': language, 'TaggedText': tagged_text, 'SourceChannel': source_channel, })
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return SampleInstance(
self._version,
payload,
assistant_sid=self._solution['assistant_sid'],
task_sid=self._solution['task_sid'],
sid=self._solution['sid'],
)
def delete(self):
"""
Deletes the SampleInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Autopilot.V1.SampleContext {}>'.format(context)
class SampleInstance(InstanceResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, payload, assistant_sid, task_sid, sid=None):
"""
Initialize the SampleInstance
:returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance
"""
super(SampleInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'account_sid': payload.get('account_sid'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'task_sid': payload.get('task_sid'),
'language': payload.get('language'),
'assistant_sid': payload.get('assistant_sid'),
'sid': payload.get('sid'),
'tagged_text': payload.get('tagged_text'),
'url': payload.get('url'),
'source_channel': payload.get('source_channel'),
}
# Context
self._context = None
self._solution = {
'assistant_sid': assistant_sid,
'task_sid': task_sid,
'sid': sid or self._properties['sid'],
}
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SampleContext for this SampleInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleContext
"""
if self._context is None:
self._context = SampleContext(
self._version,
assistant_sid=self._solution['assistant_sid'],
task_sid=self._solution['task_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def date_created(self):
"""
:returns: The RFC 2822 date and time in GMT when the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The RFC 2822 date and time in GMT when the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def task_sid(self):
"""
:returns: The SID of the Task associated with the resource
:rtype: unicode
"""
return self._properties['task_sid']
@property
def language(self):
"""
:returns: An ISO language-country string that specifies the language used for the sample
:rtype: unicode
"""
return self._properties['language']
@property
def assistant_sid(self):
"""
:returns: The SID of the Assistant that is the parent of the Task associated with the resource
:rtype: unicode
"""
return self._properties['assistant_sid']
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def tagged_text(self):
"""
:returns: The text example of how end users might express the task
:rtype: unicode
"""
return self._properties['tagged_text']
@property
def url(self):
"""
:returns: The absolute URL of the Sample resource
:rtype: unicode
"""
return self._properties['url']
@property
def source_channel(self):
"""
:returns: The communication channel from which the sample was captured
:rtype: unicode
"""
return self._properties['source_channel']
def fetch(self):
"""
Fetch the SampleInstance
:returns: The fetched SampleInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance
"""
return self._proxy.fetch()
def update(self, language=values.unset, tagged_text=values.unset,
source_channel=values.unset):
"""
Update the SampleInstance
:param unicode language: The ISO language-country string that specifies the language used for the sample
:param unicode tagged_text: The text example of how end users might express the task
:param unicode source_channel: The communication channel from which the sample was captured
:returns: The updated SampleInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance
"""
return self._proxy.update(language=language, tagged_text=tagged_text, source_channel=source_channel, )
def delete(self):
"""
Deletes the SampleInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Autopilot.V1.SampleInstance {}>'.format(context)
| mit | b462500b3a6d36c68a801bcd58143315 | 36.226721 | 123 | 0.625992 | 4.41113 | false | false | false | false |
twilio/twilio-python | twilio/rest/voice/v1/connection_policy/__init__.py | 1 | 14675 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
from twilio.rest.voice.v1.connection_policy.connection_policy_target import ConnectionPolicyTargetList
class ConnectionPolicyList(ListResource):
def __init__(self, version):
"""
Initialize the ConnectionPolicyList
:param Version version: Version that contains the resource
:returns: twilio.rest.voice.v1.connection_policy.ConnectionPolicyList
:rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyList
"""
super(ConnectionPolicyList, self).__init__(version)
# Path Solution
self._solution = {}
self._uri = '/ConnectionPolicies'.format(**self._solution)
def create(self, friendly_name=values.unset):
"""
Create the ConnectionPolicyInstance
:param unicode friendly_name: A string to describe the resource
:returns: The created ConnectionPolicyInstance
:rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance
"""
data = values.of({'FriendlyName': friendly_name, })
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return ConnectionPolicyInstance(self._version, payload, )
def stream(self, limit=None, page_size=None):
"""
Streams ConnectionPolicyInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, limit=None, page_size=None):
"""
Lists ConnectionPolicyInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance]
"""
return list(self.stream(limit=limit, page_size=page_size, ))
def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of ConnectionPolicyInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of ConnectionPolicyInstance
:rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyPage
"""
data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })
response = self._version.page(method='GET', uri=self._uri, params=data, )
return ConnectionPolicyPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of ConnectionPolicyInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of ConnectionPolicyInstance
:rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return ConnectionPolicyPage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a ConnectionPolicyContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.voice.v1.connection_policy.ConnectionPolicyContext
:rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyContext
"""
return ConnectionPolicyContext(self._version, sid=sid, )
def __call__(self, sid):
"""
Constructs a ConnectionPolicyContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.voice.v1.connection_policy.ConnectionPolicyContext
:rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyContext
"""
return ConnectionPolicyContext(self._version, sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Voice.V1.ConnectionPolicyList>'
class ConnectionPolicyPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the ConnectionPolicyPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.voice.v1.connection_policy.ConnectionPolicyPage
:rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyPage
"""
super(ConnectionPolicyPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of ConnectionPolicyInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance
:rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance
"""
return ConnectionPolicyInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Voice.V1.ConnectionPolicyPage>'
class ConnectionPolicyContext(InstanceContext):
def __init__(self, version, sid):
"""
Initialize the ConnectionPolicyContext
:param Version version: Version that contains the resource
:param sid: The unique string that identifies the resource
:returns: twilio.rest.voice.v1.connection_policy.ConnectionPolicyContext
:rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyContext
"""
super(ConnectionPolicyContext, self).__init__(version)
# Path Solution
self._solution = {'sid': sid, }
self._uri = '/ConnectionPolicies/{sid}'.format(**self._solution)
# Dependents
self._targets = None
def fetch(self):
"""
Fetch the ConnectionPolicyInstance
:returns: The fetched ConnectionPolicyInstance
:rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return ConnectionPolicyInstance(self._version, payload, sid=self._solution['sid'], )
def update(self, friendly_name=values.unset):
"""
Update the ConnectionPolicyInstance
:param unicode friendly_name: A string to describe the resource
:returns: The updated ConnectionPolicyInstance
:rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance
"""
data = values.of({'FriendlyName': friendly_name, })
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return ConnectionPolicyInstance(self._version, payload, sid=self._solution['sid'], )
def delete(self):
"""
Deletes the ConnectionPolicyInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
@property
def targets(self):
"""
Access the targets
:returns: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetList
:rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetList
"""
if self._targets is None:
self._targets = ConnectionPolicyTargetList(
self._version,
connection_policy_sid=self._solution['sid'],
)
return self._targets
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Voice.V1.ConnectionPolicyContext {}>'.format(context)
class ConnectionPolicyInstance(InstanceResource):
def __init__(self, version, payload, sid=None):
"""
Initialize the ConnectionPolicyInstance
:returns: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance
:rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance
"""
super(ConnectionPolicyInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'account_sid': payload.get('account_sid'),
'sid': payload.get('sid'),
'friendly_name': payload.get('friendly_name'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'url': payload.get('url'),
'links': payload.get('links'),
}
# Context
self._context = None
self._solution = {'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ConnectionPolicyContext for this ConnectionPolicyInstance
:rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyContext
"""
if self._context is None:
self._context = ConnectionPolicyContext(self._version, sid=self._solution['sid'], )
return self._context
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def friendly_name(self):
"""
:returns: The string that you assigned to describe the resource
:rtype: unicode
"""
return self._properties['friendly_name']
@property
def date_created(self):
"""
:returns: The RFC 2822 date and time in GMT when the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The RFC 2822 date and time in GMT when the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def url(self):
"""
:returns: The absolute URL of the resource
:rtype: unicode
"""
return self._properties['url']
@property
def links(self):
"""
:returns: The URLs of related resources
:rtype: unicode
"""
return self._properties['links']
def fetch(self):
"""
Fetch the ConnectionPolicyInstance
:returns: The fetched ConnectionPolicyInstance
:rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance
"""
return self._proxy.fetch()
def update(self, friendly_name=values.unset):
"""
Update the ConnectionPolicyInstance
:param unicode friendly_name: A string to describe the resource
:returns: The updated ConnectionPolicyInstance
:rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance
"""
return self._proxy.update(friendly_name=friendly_name, )
def delete(self):
"""
Deletes the ConnectionPolicyInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
@property
def targets(self):
"""
Access the targets
:returns: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetList
:rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetList
"""
return self._proxy.targets
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Voice.V1.ConnectionPolicyInstance {}>'.format(context)
| mit | d346834c25f5bc0ee3c71b5c8b52fd81 | 33.857482 | 108 | 0.637411 | 4.532119 | false | false | false | false |
twilio/twilio-python | twilio/rest/microvisor/v1/app.py | 1 | 11930 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class AppList(ListResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version):
"""
Initialize the AppList
:param Version version: Version that contains the resource
:returns: twilio.rest.microvisor.v1.app.AppList
:rtype: twilio.rest.microvisor.v1.app.AppList
"""
super(AppList, self).__init__(version)
# Path Solution
self._solution = {}
self._uri = '/Apps'.format(**self._solution)
def stream(self, limit=None, page_size=None):
"""
Streams AppInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.microvisor.v1.app.AppInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, limit=None, page_size=None):
"""
Lists AppInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.microvisor.v1.app.AppInstance]
"""
return list(self.stream(limit=limit, page_size=page_size, ))
def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of AppInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of AppInstance
:rtype: twilio.rest.microvisor.v1.app.AppPage
"""
data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })
response = self._version.page(method='GET', uri=self._uri, params=data, )
return AppPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of AppInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of AppInstance
:rtype: twilio.rest.microvisor.v1.app.AppPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return AppPage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a AppContext
:param sid: A string that uniquely identifies this App.
:returns: twilio.rest.microvisor.v1.app.AppContext
:rtype: twilio.rest.microvisor.v1.app.AppContext
"""
return AppContext(self._version, sid=sid, )
def __call__(self, sid):
"""
Constructs a AppContext
:param sid: A string that uniquely identifies this App.
:returns: twilio.rest.microvisor.v1.app.AppContext
:rtype: twilio.rest.microvisor.v1.app.AppContext
"""
return AppContext(self._version, sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Microvisor.V1.AppList>'
class AppPage(Page):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, response, solution):
"""
Initialize the AppPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.microvisor.v1.app.AppPage
:rtype: twilio.rest.microvisor.v1.app.AppPage
"""
super(AppPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of AppInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.microvisor.v1.app.AppInstance
:rtype: twilio.rest.microvisor.v1.app.AppInstance
"""
return AppInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Microvisor.V1.AppPage>'
class AppContext(InstanceContext):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, sid):
"""
Initialize the AppContext
:param Version version: Version that contains the resource
:param sid: A string that uniquely identifies this App.
:returns: twilio.rest.microvisor.v1.app.AppContext
:rtype: twilio.rest.microvisor.v1.app.AppContext
"""
super(AppContext, self).__init__(version)
# Path Solution
self._solution = {'sid': sid, }
self._uri = '/Apps/{sid}'.format(**self._solution)
def fetch(self):
"""
Fetch the AppInstance
:returns: The fetched AppInstance
:rtype: twilio.rest.microvisor.v1.app.AppInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return AppInstance(self._version, payload, sid=self._solution['sid'], )
def delete(self):
"""
Deletes the AppInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Microvisor.V1.AppContext {}>'.format(context)
class AppInstance(InstanceResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, payload, sid=None):
"""
Initialize the AppInstance
:returns: twilio.rest.microvisor.v1.app.AppInstance
:rtype: twilio.rest.microvisor.v1.app.AppInstance
"""
super(AppInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'account_sid': payload.get('account_sid'),
'hash': payload.get('hash'),
'unique_name': payload.get('unique_name'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: AppContext for this AppInstance
:rtype: twilio.rest.microvisor.v1.app.AppContext
"""
if self._context is None:
self._context = AppContext(self._version, sid=self._solution['sid'], )
return self._context
@property
def sid(self):
"""
:returns: A string that uniquely identifies this App.
:rtype: unicode
"""
return self._properties['sid']
@property
def account_sid(self):
"""
:returns: The Account SID.
:rtype: unicode
"""
return self._properties['account_sid']
@property
def hash(self):
"""
:returns: App manifest hash represented as hash_algorithm:hash_value.
:rtype: unicode
"""
return self._properties['hash']
@property
def unique_name(self):
"""
:returns: An developer-defined string that uniquely identifies the App.
:rtype: unicode
"""
return self._properties['unique_name']
@property
def date_created(self):
"""
:returns: The date that this App was created.
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The date that this App was last updated.
:rtype: datetime
"""
return self._properties['date_updated']
@property
def url(self):
"""
:returns: The URL of this resource.
:rtype: unicode
"""
return self._properties['url']
def fetch(self):
"""
Fetch the AppInstance
:returns: The fetched AppInstance
:rtype: twilio.rest.microvisor.v1.app.AppInstance
"""
return self._proxy.fetch()
def delete(self):
"""
Deletes the AppInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Microvisor.V1.AppInstance {}>'.format(context)
| mit | 6ccdacea52c90c7d20ce2ee0417d6e52 | 31.865014 | 97 | 0.607712 | 4.314647 | false | false | false | false |
twilio/twilio-python | twilio/rest/preview/trusted_comms/current_call.py | 1 | 10840 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class CurrentCallList(ListResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version):
"""
Initialize the CurrentCallList
:param Version version: Version that contains the resource
:returns: twilio.rest.preview.trusted_comms.current_call.CurrentCallList
:rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallList
"""
super(CurrentCallList, self).__init__(version)
# Path Solution
self._solution = {}
def get(self):
"""
Constructs a CurrentCallContext
:returns: twilio.rest.preview.trusted_comms.current_call.CurrentCallContext
:rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallContext
"""
return CurrentCallContext(self._version, )
def __call__(self):
"""
Constructs a CurrentCallContext
:returns: twilio.rest.preview.trusted_comms.current_call.CurrentCallContext
:rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallContext
"""
return CurrentCallContext(self._version, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Preview.TrustedComms.CurrentCallList>'
class CurrentCallPage(Page):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, response, solution):
"""
Initialize the CurrentCallPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.preview.trusted_comms.current_call.CurrentCallPage
:rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallPage
"""
super(CurrentCallPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of CurrentCallInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.preview.trusted_comms.current_call.CurrentCallInstance
:rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallInstance
"""
return CurrentCallInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Preview.TrustedComms.CurrentCallPage>'
class CurrentCallContext(InstanceContext):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version):
"""
Initialize the CurrentCallContext
:param Version version: Version that contains the resource
:returns: twilio.rest.preview.trusted_comms.current_call.CurrentCallContext
:rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallContext
"""
super(CurrentCallContext, self).__init__(version)
# Path Solution
self._solution = {}
self._uri = '/CurrentCall'.format(**self._solution)
def fetch(self, x_xcnam_sensitive_phone_number_from=values.unset,
x_xcnam_sensitive_phone_number_to=values.unset):
"""
Fetch the CurrentCallInstance
:param unicode x_xcnam_sensitive_phone_number_from: The originating Phone Number
:param unicode x_xcnam_sensitive_phone_number_to: The terminating Phone Number
:returns: The fetched CurrentCallInstance
:rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallInstance
"""
headers = values.of({
'X-Xcnam-Sensitive-Phone-Number-From': x_xcnam_sensitive_phone_number_from,
'X-Xcnam-Sensitive-Phone-Number-To': x_xcnam_sensitive_phone_number_to,
})
payload = self._version.fetch(method='GET', uri=self._uri, headers=headers, )
return CurrentCallInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Preview.TrustedComms.CurrentCallContext {}>'.format(context)
class CurrentCallInstance(InstanceResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, payload):
"""
Initialize the CurrentCallInstance
:returns: twilio.rest.preview.trusted_comms.current_call.CurrentCallInstance
:rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallInstance
"""
super(CurrentCallInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'bg_color': payload.get('bg_color'),
'caller': payload.get('caller'),
'created_at': deserialize.iso8601_datetime(payload.get('created_at')),
'font_color': payload.get('font_color'),
'from_': payload.get('from'),
'logo': payload.get('logo'),
'manager': payload.get('manager'),
'reason': payload.get('reason'),
'shield_img': payload.get('shield_img'),
'sid': payload.get('sid'),
'status': payload.get('status'),
'to': payload.get('to'),
'url': payload.get('url'),
'use_case': payload.get('use_case'),
}
# Context
self._context = None
self._solution = {}
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: CurrentCallContext for this CurrentCallInstance
:rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallContext
"""
if self._context is None:
self._context = CurrentCallContext(self._version, )
return self._context
@property
def bg_color(self):
"""
:returns: Background color of the current phone call
:rtype: unicode
"""
return self._properties['bg_color']
@property
def caller(self):
"""
:returns: Caller name of the current phone call
:rtype: unicode
"""
return self._properties['caller']
@property
def created_at(self):
"""
:returns: The date this current phone call was created
:rtype: datetime
"""
return self._properties['created_at']
@property
def font_color(self):
"""
:returns: Font color of the current phone call
:rtype: unicode
"""
return self._properties['font_color']
@property
def from_(self):
"""
:returns: The originating phone number
:rtype: unicode
"""
return self._properties['from_']
@property
def logo(self):
"""
:returns: Logo URL of the caller
:rtype: unicode
"""
return self._properties['logo']
@property
def manager(self):
"""
:returns: The name of the CPS organization
:rtype: unicode
"""
return self._properties['manager']
@property
def reason(self):
"""
:returns: The business reason for this current phone call
:rtype: unicode
"""
return self._properties['reason']
@property
def shield_img(self):
"""
:returns: Shield image URL that serves as authenticity proof of the current phone call
:rtype: unicode
"""
return self._properties['shield_img']
@property
def sid(self):
"""
:returns: A string that uniquely identifies this current branded phone call.
:rtype: unicode
"""
return self._properties['sid']
@property
def status(self):
"""
:returns: The status of the current phone call
:rtype: unicode
"""
return self._properties['status']
@property
def to(self):
"""
:returns: The terminating phone number
:rtype: unicode
"""
return self._properties['to']
@property
def url(self):
"""
:returns: The URL of this resource.
:rtype: unicode
"""
return self._properties['url']
@property
def use_case(self):
"""
:returns: The use case for the current phone call
:rtype: unicode
"""
return self._properties['use_case']
def fetch(self, x_xcnam_sensitive_phone_number_from=values.unset,
x_xcnam_sensitive_phone_number_to=values.unset):
"""
Fetch the CurrentCallInstance
:param unicode x_xcnam_sensitive_phone_number_from: The originating Phone Number
:param unicode x_xcnam_sensitive_phone_number_to: The terminating Phone Number
:returns: The fetched CurrentCallInstance
:rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallInstance
"""
return self._proxy.fetch(
x_xcnam_sensitive_phone_number_from=x_xcnam_sensitive_phone_number_from,
x_xcnam_sensitive_phone_number_to=x_xcnam_sensitive_phone_number_to,
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Preview.TrustedComms.CurrentCallInstance {}>'.format(context)
| mit | 796b60d0d82493789c2bb9e3363c2b42 | 30.788856 | 94 | 0.619649 | 4.311854 | false | false | false | false |
twilio/twilio-python | twilio/rest/ip_messaging/v2/service/user/user_binding.py | 1 | 14897 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class UserBindingList(ListResource):
def __init__(self, version, service_sid, user_sid):
"""
Initialize the UserBindingList
:param Version version: Version that contains the resource
:param service_sid: The service_sid
:param user_sid: The user_sid
:returns: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingList
:rtype: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingList
"""
super(UserBindingList, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, 'user_sid': user_sid, }
self._uri = '/Services/{service_sid}/Users/{user_sid}/Bindings'.format(**self._solution)
def stream(self, binding_type=values.unset, limit=None, page_size=None):
"""
Streams UserBindingInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param list[UserBindingInstance.BindingType] binding_type: The binding_type
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(binding_type=binding_type, page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, binding_type=values.unset, limit=None, page_size=None):
"""
Lists UserBindingInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param list[UserBindingInstance.BindingType] binding_type: The binding_type
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingInstance]
"""
return list(self.stream(binding_type=binding_type, limit=limit, page_size=page_size, ))
def page(self, binding_type=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
"""
Retrieve a single page of UserBindingInstance records from the API.
Request is executed immediately
:param list[UserBindingInstance.BindingType] binding_type: The binding_type
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of UserBindingInstance
:rtype: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingPage
"""
data = values.of({
'BindingType': serialize.map(binding_type, lambda e: e),
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(method='GET', uri=self._uri, params=data, )
return UserBindingPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of UserBindingInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of UserBindingInstance
:rtype: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return UserBindingPage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a UserBindingContext
:param sid: The sid
:returns: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingContext
:rtype: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingContext
"""
return UserBindingContext(
self._version,
service_sid=self._solution['service_sid'],
user_sid=self._solution['user_sid'],
sid=sid,
)
def __call__(self, sid):
"""
Constructs a UserBindingContext
:param sid: The sid
:returns: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingContext
:rtype: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingContext
"""
return UserBindingContext(
self._version,
service_sid=self._solution['service_sid'],
user_sid=self._solution['user_sid'],
sid=sid,
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.IpMessaging.V2.UserBindingList>'
class UserBindingPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the UserBindingPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param service_sid: The service_sid
:param user_sid: The user_sid
:returns: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingPage
:rtype: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingPage
"""
super(UserBindingPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of UserBindingInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingInstance
:rtype: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingInstance
"""
return UserBindingInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
user_sid=self._solution['user_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.IpMessaging.V2.UserBindingPage>'
class UserBindingContext(InstanceContext):
def __init__(self, version, service_sid, user_sid, sid):
"""
Initialize the UserBindingContext
:param Version version: Version that contains the resource
:param service_sid: The service_sid
:param user_sid: The user_sid
:param sid: The sid
:returns: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingContext
:rtype: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingContext
"""
super(UserBindingContext, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, 'user_sid': user_sid, 'sid': sid, }
self._uri = '/Services/{service_sid}/Users/{user_sid}/Bindings/{sid}'.format(**self._solution)
def fetch(self):
"""
Fetch the UserBindingInstance
:returns: The fetched UserBindingInstance
:rtype: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return UserBindingInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
user_sid=self._solution['user_sid'],
sid=self._solution['sid'],
)
def delete(self):
"""
Deletes the UserBindingInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.IpMessaging.V2.UserBindingContext {}>'.format(context)
class UserBindingInstance(InstanceResource):
class BindingType(object):
GCM = "gcm"
APN = "apn"
FCM = "fcm"
def __init__(self, version, payload, service_sid, user_sid, sid=None):
"""
Initialize the UserBindingInstance
:returns: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingInstance
:rtype: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingInstance
"""
super(UserBindingInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'account_sid': payload.get('account_sid'),
'service_sid': payload.get('service_sid'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'endpoint': payload.get('endpoint'),
'identity': payload.get('identity'),
'user_sid': payload.get('user_sid'),
'credential_sid': payload.get('credential_sid'),
'binding_type': payload.get('binding_type'),
'message_types': payload.get('message_types'),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {
'service_sid': service_sid,
'user_sid': user_sid,
'sid': sid or self._properties['sid'],
}
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: UserBindingContext for this UserBindingInstance
:rtype: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingContext
"""
if self._context is None:
self._context = UserBindingContext(
self._version,
service_sid=self._solution['service_sid'],
user_sid=self._solution['user_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def sid(self):
"""
:returns: The sid
:rtype: unicode
"""
return self._properties['sid']
@property
def account_sid(self):
"""
:returns: The account_sid
:rtype: unicode
"""
return self._properties['account_sid']
@property
def service_sid(self):
"""
:returns: The service_sid
:rtype: unicode
"""
return self._properties['service_sid']
@property
def date_created(self):
"""
:returns: The date_created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The date_updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def endpoint(self):
"""
:returns: The endpoint
:rtype: unicode
"""
return self._properties['endpoint']
@property
def identity(self):
"""
:returns: The identity
:rtype: unicode
"""
return self._properties['identity']
@property
def user_sid(self):
"""
:returns: The user_sid
:rtype: unicode
"""
return self._properties['user_sid']
@property
def credential_sid(self):
"""
:returns: The credential_sid
:rtype: unicode
"""
return self._properties['credential_sid']
@property
def binding_type(self):
"""
:returns: The binding_type
:rtype: UserBindingInstance.BindingType
"""
return self._properties['binding_type']
@property
def message_types(self):
"""
:returns: The message_types
:rtype: list[unicode]
"""
return self._properties['message_types']
@property
def url(self):
"""
:returns: The url
:rtype: unicode
"""
return self._properties['url']
def fetch(self):
"""
Fetch the UserBindingInstance
:returns: The fetched UserBindingInstance
:rtype: twilio.rest.ip_messaging.v2.service.user.user_binding.UserBindingInstance
"""
return self._proxy.fetch()
def delete(self):
"""
Deletes the UserBindingInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.IpMessaging.V2.UserBindingInstance {}>'.format(context)
| mit | b6f0cdf32f4b90d63374218615d6d9cb | 32.401345 | 102 | 0.603947 | 4.274605 | false | false | false | false |
twilio/twilio-python | tests/integration/chat/v1/service/user/test_user_channel.py | 1 | 3943 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class UserChannelTestCase(IntegrationTestCase):
def test_list_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.chat.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.user_channels.list()
self.holodeck.assert_has_request(Request(
'get',
'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels',
))
def test_read_full_response(self):
self.holodeck.mock(Response(
200,
'''
{
"meta": {
"page": 0,
"page_size": 50,
"first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0",
"previous_page_url": null,
"url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0",
"next_page_url": null,
"key": "channels"
},
"channels": [
{
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"member_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"status": "joined",
"last_consumed_message_index": 5,
"unread_messages_count": 5,
"links": {
"channel": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"member": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
}
]
}
'''
))
actual = self.client.chat.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.user_channels.list()
self.assertIsNotNone(actual)
def test_read_empty_response(self):
self.holodeck.mock(Response(
200,
'''
{
"meta": {
"page": 0,
"page_size": 50,
"first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0",
"previous_page_url": null,
"url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0",
"next_page_url": null,
"key": "channels"
},
"channels": []
}
'''
))
actual = self.client.chat.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.user_channels.list()
self.assertIsNotNone(actual)
| mit | e72e94d8f8231684eab818255d91b23f | 41.858696 | 197 | 0.541466 | 4.904229 | false | true | false | false |
twilio/twilio-python | twilio/rest/conversations/v1/service/participant_conversation.py | 1 | 13877 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class ParticipantConversationList(ListResource):
def __init__(self, version, chat_service_sid):
"""
Initialize the ParticipantConversationList
:param Version version: Version that contains the resource
:param chat_service_sid: The unique ID of the Conversation Service this conversation belongs to.
:returns: twilio.rest.conversations.v1.service.participant_conversation.ParticipantConversationList
:rtype: twilio.rest.conversations.v1.service.participant_conversation.ParticipantConversationList
"""
super(ParticipantConversationList, self).__init__(version)
# Path Solution
self._solution = {'chat_service_sid': chat_service_sid, }
self._uri = '/Services/{chat_service_sid}/ParticipantConversations'.format(**self._solution)
def stream(self, identity=values.unset, address=values.unset, limit=None,
page_size=None):
"""
Streams ParticipantConversationInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param unicode identity: A unique string identifier for the conversation participant as Conversation User.
:param unicode address: A unique string identifier for the conversation participant who's not a Conversation User.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.conversations.v1.service.participant_conversation.ParticipantConversationInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(identity=identity, address=address, page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, identity=values.unset, address=values.unset, limit=None,
page_size=None):
"""
Lists ParticipantConversationInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param unicode identity: A unique string identifier for the conversation participant as Conversation User.
:param unicode address: A unique string identifier for the conversation participant who's not a Conversation User.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.conversations.v1.service.participant_conversation.ParticipantConversationInstance]
"""
return list(self.stream(identity=identity, address=address, limit=limit, page_size=page_size, ))
def page(self, identity=values.unset, address=values.unset,
page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of ParticipantConversationInstance records from the API.
Request is executed immediately
:param unicode identity: A unique string identifier for the conversation participant as Conversation User.
:param unicode address: A unique string identifier for the conversation participant who's not a Conversation User.
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of ParticipantConversationInstance
:rtype: twilio.rest.conversations.v1.service.participant_conversation.ParticipantConversationPage
"""
data = values.of({
'Identity': identity,
'Address': address,
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(method='GET', uri=self._uri, params=data, )
return ParticipantConversationPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of ParticipantConversationInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of ParticipantConversationInstance
:rtype: twilio.rest.conversations.v1.service.participant_conversation.ParticipantConversationPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return ParticipantConversationPage(self._version, response, self._solution)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Conversations.V1.ParticipantConversationList>'
class ParticipantConversationPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the ParticipantConversationPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param chat_service_sid: The unique ID of the Conversation Service this conversation belongs to.
:returns: twilio.rest.conversations.v1.service.participant_conversation.ParticipantConversationPage
:rtype: twilio.rest.conversations.v1.service.participant_conversation.ParticipantConversationPage
"""
super(ParticipantConversationPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of ParticipantConversationInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.conversations.v1.service.participant_conversation.ParticipantConversationInstance
:rtype: twilio.rest.conversations.v1.service.participant_conversation.ParticipantConversationInstance
"""
return ParticipantConversationInstance(
self._version,
payload,
chat_service_sid=self._solution['chat_service_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Conversations.V1.ParticipantConversationPage>'
class ParticipantConversationInstance(InstanceResource):
class State(object):
INACTIVE = "inactive"
ACTIVE = "active"
CLOSED = "closed"
def __init__(self, version, payload, chat_service_sid):
"""
Initialize the ParticipantConversationInstance
:returns: twilio.rest.conversations.v1.service.participant_conversation.ParticipantConversationInstance
:rtype: twilio.rest.conversations.v1.service.participant_conversation.ParticipantConversationInstance
"""
super(ParticipantConversationInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'account_sid': payload.get('account_sid'),
'chat_service_sid': payload.get('chat_service_sid'),
'participant_sid': payload.get('participant_sid'),
'participant_user_sid': payload.get('participant_user_sid'),
'participant_identity': payload.get('participant_identity'),
'participant_messaging_binding': payload.get('participant_messaging_binding'),
'conversation_sid': payload.get('conversation_sid'),
'conversation_unique_name': payload.get('conversation_unique_name'),
'conversation_friendly_name': payload.get('conversation_friendly_name'),
'conversation_attributes': payload.get('conversation_attributes'),
'conversation_date_created': deserialize.iso8601_datetime(payload.get('conversation_date_created')),
'conversation_date_updated': deserialize.iso8601_datetime(payload.get('conversation_date_updated')),
'conversation_created_by': payload.get('conversation_created_by'),
'conversation_state': payload.get('conversation_state'),
'conversation_timers': payload.get('conversation_timers'),
'links': payload.get('links'),
}
# Context
self._context = None
self._solution = {'chat_service_sid': chat_service_sid, }
@property
def account_sid(self):
"""
:returns: The unique ID of the Account responsible for this conversation.
:rtype: unicode
"""
return self._properties['account_sid']
@property
def chat_service_sid(self):
"""
:returns: The unique ID of the Conversation Service this conversation belongs to.
:rtype: unicode
"""
return self._properties['chat_service_sid']
@property
def participant_sid(self):
"""
:returns: The unique ID of the Participant.
:rtype: unicode
"""
return self._properties['participant_sid']
@property
def participant_user_sid(self):
"""
:returns: The unique ID for the conversation participant as Conversation User.
:rtype: unicode
"""
return self._properties['participant_user_sid']
@property
def participant_identity(self):
"""
:returns: A unique string identifier for the conversation participant as Conversation User.
:rtype: unicode
"""
return self._properties['participant_identity']
@property
def participant_messaging_binding(self):
"""
:returns: Information about how this participant exchanges messages with the conversation.
:rtype: dict
"""
return self._properties['participant_messaging_binding']
@property
def conversation_sid(self):
"""
:returns: The unique ID of the Conversation this Participant belongs to.
:rtype: unicode
"""
return self._properties['conversation_sid']
@property
def conversation_unique_name(self):
"""
:returns: An application-defined string that uniquely identifies the Conversation resource.
:rtype: unicode
"""
return self._properties['conversation_unique_name']
@property
def conversation_friendly_name(self):
"""
:returns: The human-readable name of this conversation.
:rtype: unicode
"""
return self._properties['conversation_friendly_name']
@property
def conversation_attributes(self):
"""
:returns: An optional string metadata field you can use to store any data you wish.
:rtype: unicode
"""
return self._properties['conversation_attributes']
@property
def conversation_date_created(self):
"""
:returns: The date that this conversation was created.
:rtype: datetime
"""
return self._properties['conversation_date_created']
@property
def conversation_date_updated(self):
"""
:returns: The date that this conversation was last updated.
:rtype: datetime
"""
return self._properties['conversation_date_updated']
@property
def conversation_created_by(self):
"""
:returns: Creator of this conversation.
:rtype: unicode
"""
return self._properties['conversation_created_by']
@property
def conversation_state(self):
"""
:returns: The current state of this User Conversation
:rtype: ParticipantConversationInstance.State
"""
return self._properties['conversation_state']
@property
def conversation_timers(self):
"""
:returns: Timer date values for this conversation.
:rtype: dict
"""
return self._properties['conversation_timers']
@property
def links(self):
"""
:returns: Absolute URLs to access the participant and conversation of this Participant Conversation.
:rtype: unicode
"""
return self._properties['links']
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Conversations.V1.ParticipantConversationInstance>'
| mit | 4c3cddcd6601b731b9dfeb4e6a7cdf04 | 38.200565 | 122 | 0.652158 | 4.572323 | false | false | false | false |
twilio/twilio-python | twilio/rest/taskrouter/v1/workspace/event.py | 1 | 19339 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class EventList(ListResource):
def __init__(self, version, workspace_sid):
"""
Initialize the EventList
:param Version version: Version that contains the resource
:param workspace_sid: The SID of the Workspace that contains the Event
:returns: twilio.rest.taskrouter.v1.workspace.event.EventList
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventList
"""
super(EventList, self).__init__(version)
# Path Solution
self._solution = {'workspace_sid': workspace_sid, }
self._uri = '/Workspaces/{workspace_sid}/Events'.format(**self._solution)
def stream(self, end_date=values.unset, event_type=values.unset,
minutes=values.unset, reservation_sid=values.unset,
start_date=values.unset, task_queue_sid=values.unset,
task_sid=values.unset, worker_sid=values.unset,
workflow_sid=values.unset, task_channel=values.unset,
sid=values.unset, limit=None, page_size=None):
"""
Streams EventInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param datetime end_date: Only include usage that occurred on or before this date
:param unicode event_type: The type of Events to read
:param unicode minutes: The period of events to read in minutes
:param unicode reservation_sid: The SID of the Reservation with the Events to read
:param datetime start_date: Only include Events from on or after this date
:param unicode task_queue_sid: The SID of the TaskQueue with the Events to read
:param unicode task_sid: The SID of the Task with the Events to read
:param unicode worker_sid: The SID of the Worker with the Events to read
:param unicode workflow_sid: The SID of the Worker with the Events to read
:param unicode task_channel: The TaskChannel with the Events to read
:param unicode sid: The unique string that identifies the resource
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.taskrouter.v1.workspace.event.EventInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(
end_date=end_date,
event_type=event_type,
minutes=minutes,
reservation_sid=reservation_sid,
start_date=start_date,
task_queue_sid=task_queue_sid,
task_sid=task_sid,
worker_sid=worker_sid,
workflow_sid=workflow_sid,
task_channel=task_channel,
sid=sid,
page_size=limits['page_size'],
)
return self._version.stream(page, limits['limit'])
def list(self, end_date=values.unset, event_type=values.unset,
minutes=values.unset, reservation_sid=values.unset,
start_date=values.unset, task_queue_sid=values.unset,
task_sid=values.unset, worker_sid=values.unset,
workflow_sid=values.unset, task_channel=values.unset, sid=values.unset,
limit=None, page_size=None):
"""
Lists EventInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param datetime end_date: Only include usage that occurred on or before this date
:param unicode event_type: The type of Events to read
:param unicode minutes: The period of events to read in minutes
:param unicode reservation_sid: The SID of the Reservation with the Events to read
:param datetime start_date: Only include Events from on or after this date
:param unicode task_queue_sid: The SID of the TaskQueue with the Events to read
:param unicode task_sid: The SID of the Task with the Events to read
:param unicode worker_sid: The SID of the Worker with the Events to read
:param unicode workflow_sid: The SID of the Worker with the Events to read
:param unicode task_channel: The TaskChannel with the Events to read
:param unicode sid: The unique string that identifies the resource
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.taskrouter.v1.workspace.event.EventInstance]
"""
return list(self.stream(
end_date=end_date,
event_type=event_type,
minutes=minutes,
reservation_sid=reservation_sid,
start_date=start_date,
task_queue_sid=task_queue_sid,
task_sid=task_sid,
worker_sid=worker_sid,
workflow_sid=workflow_sid,
task_channel=task_channel,
sid=sid,
limit=limit,
page_size=page_size,
))
def page(self, end_date=values.unset, event_type=values.unset,
minutes=values.unset, reservation_sid=values.unset,
start_date=values.unset, task_queue_sid=values.unset,
task_sid=values.unset, worker_sid=values.unset,
workflow_sid=values.unset, task_channel=values.unset, sid=values.unset,
page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of EventInstance records from the API.
Request is executed immediately
:param datetime end_date: Only include usage that occurred on or before this date
:param unicode event_type: The type of Events to read
:param unicode minutes: The period of events to read in minutes
:param unicode reservation_sid: The SID of the Reservation with the Events to read
:param datetime start_date: Only include Events from on or after this date
:param unicode task_queue_sid: The SID of the TaskQueue with the Events to read
:param unicode task_sid: The SID of the Task with the Events to read
:param unicode worker_sid: The SID of the Worker with the Events to read
:param unicode workflow_sid: The SID of the Worker with the Events to read
:param unicode task_channel: The TaskChannel with the Events to read
:param unicode sid: The unique string that identifies the resource
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of EventInstance
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventPage
"""
data = values.of({
'EndDate': serialize.iso8601_datetime(end_date),
'EventType': event_type,
'Minutes': minutes,
'ReservationSid': reservation_sid,
'StartDate': serialize.iso8601_datetime(start_date),
'TaskQueueSid': task_queue_sid,
'TaskSid': task_sid,
'WorkerSid': worker_sid,
'WorkflowSid': workflow_sid,
'TaskChannel': task_channel,
'Sid': sid,
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(method='GET', uri=self._uri, params=data, )
return EventPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of EventInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of EventInstance
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return EventPage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a EventContext
:param sid: The SID of the resource to fetch
:returns: twilio.rest.taskrouter.v1.workspace.event.EventContext
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext
"""
return EventContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, )
def __call__(self, sid):
"""
Constructs a EventContext
:param sid: The SID of the resource to fetch
:returns: twilio.rest.taskrouter.v1.workspace.event.EventContext
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext
"""
return EventContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Taskrouter.V1.EventList>'
class EventPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the EventPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param workspace_sid: The SID of the Workspace that contains the Event
:returns: twilio.rest.taskrouter.v1.workspace.event.EventPage
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventPage
"""
super(EventPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of EventInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.event.EventInstance
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventInstance
"""
return EventInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Taskrouter.V1.EventPage>'
class EventContext(InstanceContext):
def __init__(self, version, workspace_sid, sid):
"""
Initialize the EventContext
:param Version version: Version that contains the resource
:param workspace_sid: The SID of the Workspace with the Event to fetch
:param sid: The SID of the resource to fetch
:returns: twilio.rest.taskrouter.v1.workspace.event.EventContext
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext
"""
super(EventContext, self).__init__(version)
# Path Solution
self._solution = {'workspace_sid': workspace_sid, 'sid': sid, }
self._uri = '/Workspaces/{workspace_sid}/Events/{sid}'.format(**self._solution)
def fetch(self):
"""
Fetch the EventInstance
:returns: The fetched EventInstance
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return EventInstance(
self._version,
payload,
workspace_sid=self._solution['workspace_sid'],
sid=self._solution['sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Taskrouter.V1.EventContext {}>'.format(context)
class EventInstance(InstanceResource):
def __init__(self, version, payload, workspace_sid, sid=None):
"""
Initialize the EventInstance
:returns: twilio.rest.taskrouter.v1.workspace.event.EventInstance
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventInstance
"""
super(EventInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'account_sid': payload.get('account_sid'),
'actor_sid': payload.get('actor_sid'),
'actor_type': payload.get('actor_type'),
'actor_url': payload.get('actor_url'),
'description': payload.get('description'),
'event_data': payload.get('event_data'),
'event_date': deserialize.iso8601_datetime(payload.get('event_date')),
'event_date_ms': deserialize.integer(payload.get('event_date_ms')),
'event_type': payload.get('event_type'),
'resource_sid': payload.get('resource_sid'),
'resource_type': payload.get('resource_type'),
'resource_url': payload.get('resource_url'),
'sid': payload.get('sid'),
'source': payload.get('source'),
'source_ip_address': payload.get('source_ip_address'),
'url': payload.get('url'),
'workspace_sid': payload.get('workspace_sid'),
}
# Context
self._context = None
self._solution = {'workspace_sid': workspace_sid, 'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: EventContext for this EventInstance
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext
"""
if self._context is None:
self._context = EventContext(
self._version,
workspace_sid=self._solution['workspace_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def actor_sid(self):
"""
:returns: The SID of the resource that triggered the event
:rtype: unicode
"""
return self._properties['actor_sid']
@property
def actor_type(self):
"""
:returns: The type of resource that triggered the event
:rtype: unicode
"""
return self._properties['actor_type']
@property
def actor_url(self):
"""
:returns: The absolute URL of the resource that triggered the event
:rtype: unicode
"""
return self._properties['actor_url']
@property
def description(self):
"""
:returns: A description of the event
:rtype: unicode
"""
return self._properties['description']
@property
def event_data(self):
"""
:returns: Data about the event
:rtype: dict
"""
return self._properties['event_data']
@property
def event_date(self):
"""
:returns: The time the event was sent
:rtype: datetime
"""
return self._properties['event_date']
@property
def event_date_ms(self):
"""
:returns: The time the event was sent in milliseconds
:rtype: unicode
"""
return self._properties['event_date_ms']
@property
def event_type(self):
"""
:returns: The identifier for the event
:rtype: unicode
"""
return self._properties['event_type']
@property
def resource_sid(self):
"""
:returns: The SID of the object the event is most relevant to
:rtype: unicode
"""
return self._properties['resource_sid']
@property
def resource_type(self):
"""
:returns: The type of object the event is most relevant to
:rtype: unicode
"""
return self._properties['resource_type']
@property
def resource_url(self):
"""
:returns: The URL of the resource the event is most relevant to
:rtype: unicode
"""
return self._properties['resource_url']
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def source(self):
"""
:returns: Where the Event originated
:rtype: unicode
"""
return self._properties['source']
@property
def source_ip_address(self):
"""
:returns: The IP from which the Event originated
:rtype: unicode
"""
return self._properties['source_ip_address']
@property
def url(self):
"""
:returns: The absolute URL of the Event resource
:rtype: unicode
"""
return self._properties['url']
@property
def workspace_sid(self):
"""
:returns: The SID of the Workspace that contains the Event
:rtype: unicode
"""
return self._properties['workspace_sid']
def fetch(self):
"""
Fetch the EventInstance
:returns: The fetched EventInstance
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventInstance
"""
return self._proxy.fetch()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Taskrouter.V1.EventInstance {}>'.format(context)
| mit | 4555359fb6923f769cb484b102b4b822 | 35.76616 | 101 | 0.611459 | 4.355631 | false | false | false | false |
twilio/twilio-python | twilio/rest/chat/v2/service/role.py | 1 | 14387 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class RoleList(ListResource):
def __init__(self, version, service_sid):
"""
Initialize the RoleList
:param Version version: Version that contains the resource
:param service_sid: The SID of the Service that the resource is associated with
:returns: twilio.rest.chat.v2.service.role.RoleList
:rtype: twilio.rest.chat.v2.service.role.RoleList
"""
super(RoleList, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, }
self._uri = '/Services/{service_sid}/Roles'.format(**self._solution)
def create(self, friendly_name, type, permission):
"""
Create the RoleInstance
:param unicode friendly_name: A string to describe the new resource
:param RoleInstance.RoleType type: The type of role
:param list[unicode] permission: A permission the role should have
:returns: The created RoleInstance
:rtype: twilio.rest.chat.v2.service.role.RoleInstance
"""
data = values.of({
'FriendlyName': friendly_name,
'Type': type,
'Permission': serialize.map(permission, lambda e: e),
})
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], )
def stream(self, limit=None, page_size=None):
"""
Streams RoleInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.chat.v2.service.role.RoleInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, limit=None, page_size=None):
"""
Lists RoleInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.chat.v2.service.role.RoleInstance]
"""
return list(self.stream(limit=limit, page_size=page_size, ))
def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of RoleInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of RoleInstance
:rtype: twilio.rest.chat.v2.service.role.RolePage
"""
data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })
response = self._version.page(method='GET', uri=self._uri, params=data, )
return RolePage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of RoleInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of RoleInstance
:rtype: twilio.rest.chat.v2.service.role.RolePage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return RolePage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a RoleContext
:param sid: The SID of the Role resource to fetch
:returns: twilio.rest.chat.v2.service.role.RoleContext
:rtype: twilio.rest.chat.v2.service.role.RoleContext
"""
return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, )
def __call__(self, sid):
"""
Constructs a RoleContext
:param sid: The SID of the Role resource to fetch
:returns: twilio.rest.chat.v2.service.role.RoleContext
:rtype: twilio.rest.chat.v2.service.role.RoleContext
"""
return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Chat.V2.RoleList>'
class RolePage(Page):
def __init__(self, version, response, solution):
"""
Initialize the RolePage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param service_sid: The SID of the Service that the resource is associated with
:returns: twilio.rest.chat.v2.service.role.RolePage
:rtype: twilio.rest.chat.v2.service.role.RolePage
"""
super(RolePage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of RoleInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.chat.v2.service.role.RoleInstance
:rtype: twilio.rest.chat.v2.service.role.RoleInstance
"""
return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Chat.V2.RolePage>'
class RoleContext(InstanceContext):
def __init__(self, version, service_sid, sid):
"""
Initialize the RoleContext
:param Version version: Version that contains the resource
:param service_sid: The SID of the Service to fetch the resource from
:param sid: The SID of the Role resource to fetch
:returns: twilio.rest.chat.v2.service.role.RoleContext
:rtype: twilio.rest.chat.v2.service.role.RoleContext
"""
super(RoleContext, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, 'sid': sid, }
self._uri = '/Services/{service_sid}/Roles/{sid}'.format(**self._solution)
def fetch(self):
"""
Fetch the RoleInstance
:returns: The fetched RoleInstance
:rtype: twilio.rest.chat.v2.service.role.RoleInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return RoleInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
sid=self._solution['sid'],
)
def delete(self):
"""
Deletes the RoleInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def update(self, permission):
"""
Update the RoleInstance
:param list[unicode] permission: A permission the role should have
:returns: The updated RoleInstance
:rtype: twilio.rest.chat.v2.service.role.RoleInstance
"""
data = values.of({'Permission': serialize.map(permission, lambda e: e), })
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return RoleInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
sid=self._solution['sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Chat.V2.RoleContext {}>'.format(context)
class RoleInstance(InstanceResource):
class RoleType(object):
CHANNEL = "channel"
DEPLOYMENT = "deployment"
def __init__(self, version, payload, service_sid, sid=None):
"""
Initialize the RoleInstance
:returns: twilio.rest.chat.v2.service.role.RoleInstance
:rtype: twilio.rest.chat.v2.service.role.RoleInstance
"""
super(RoleInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'account_sid': payload.get('account_sid'),
'service_sid': payload.get('service_sid'),
'friendly_name': payload.get('friendly_name'),
'type': payload.get('type'),
'permissions': payload.get('permissions'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: RoleContext for this RoleInstance
:rtype: twilio.rest.chat.v2.service.role.RoleContext
"""
if self._context is None:
self._context = RoleContext(
self._version,
service_sid=self._solution['service_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def service_sid(self):
"""
:returns: The SID of the Service that the resource is associated with
:rtype: unicode
"""
return self._properties['service_sid']
@property
def friendly_name(self):
"""
:returns: The string that you assigned to describe the resource
:rtype: unicode
"""
return self._properties['friendly_name']
@property
def type(self):
"""
:returns: The type of role
:rtype: RoleInstance.RoleType
"""
return self._properties['type']
@property
def permissions(self):
"""
:returns: An array of the permissions the role has been granted
:rtype: list[unicode]
"""
return self._properties['permissions']
@property
def date_created(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def url(self):
"""
:returns: The absolute URL of the Role resource
:rtype: unicode
"""
return self._properties['url']
def fetch(self):
"""
Fetch the RoleInstance
:returns: The fetched RoleInstance
:rtype: twilio.rest.chat.v2.service.role.RoleInstance
"""
return self._proxy.fetch()
def delete(self):
"""
Deletes the RoleInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def update(self, permission):
"""
Update the RoleInstance
:param list[unicode] permission: A permission the role should have
:returns: The updated RoleInstance
:rtype: twilio.rest.chat.v2.service.role.RoleInstance
"""
return self._proxy.update(permission, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Chat.V2.RoleInstance {}>'.format(context)
| mit | bb394618027aee30d9b54b02b037cdb5 | 31.847032 | 97 | 0.602002 | 4.32042 | false | false | false | false |
twilio/twilio-python | twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py | 1 | 11383 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class WorkflowRealTimeStatisticsList(ListResource):
def __init__(self, version, workspace_sid, workflow_sid):
"""
Initialize the WorkflowRealTimeStatisticsList
:param Version version: Version that contains the resource
:param workspace_sid: The SID of the Workspace that contains the Workflow.
:param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsList
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsList
"""
super(WorkflowRealTimeStatisticsList, self).__init__(version)
# Path Solution
self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, }
def get(self):
"""
Constructs a WorkflowRealTimeStatisticsContext
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext
"""
return WorkflowRealTimeStatisticsContext(
self._version,
workspace_sid=self._solution['workspace_sid'],
workflow_sid=self._solution['workflow_sid'],
)
def __call__(self):
"""
Constructs a WorkflowRealTimeStatisticsContext
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext
"""
return WorkflowRealTimeStatisticsContext(
self._version,
workspace_sid=self._solution['workspace_sid'],
workflow_sid=self._solution['workflow_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Taskrouter.V1.WorkflowRealTimeStatisticsList>'
class WorkflowRealTimeStatisticsPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the WorkflowRealTimeStatisticsPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param workspace_sid: The SID of the Workspace that contains the Workflow.
:param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsPage
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsPage
"""
super(WorkflowRealTimeStatisticsPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of WorkflowRealTimeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsInstance
"""
return WorkflowRealTimeStatisticsInstance(
self._version,
payload,
workspace_sid=self._solution['workspace_sid'],
workflow_sid=self._solution['workflow_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Taskrouter.V1.WorkflowRealTimeStatisticsPage>'
class WorkflowRealTimeStatisticsContext(InstanceContext):
def __init__(self, version, workspace_sid, workflow_sid):
"""
Initialize the WorkflowRealTimeStatisticsContext
:param Version version: Version that contains the resource
:param workspace_sid: The SID of the Workspace with the Workflow to fetch
:param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext
"""
super(WorkflowRealTimeStatisticsContext, self).__init__(version)
# Path Solution
self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, }
self._uri = '/Workspaces/{workspace_sid}/Workflows/{workflow_sid}/RealTimeStatistics'.format(**self._solution)
def fetch(self, task_channel=values.unset):
"""
Fetch the WorkflowRealTimeStatisticsInstance
:param unicode task_channel: Only calculate real-time statistics on this TaskChannel
:returns: The fetched WorkflowRealTimeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsInstance
"""
data = values.of({'TaskChannel': task_channel, })
payload = self._version.fetch(method='GET', uri=self._uri, params=data, )
return WorkflowRealTimeStatisticsInstance(
self._version,
payload,
workspace_sid=self._solution['workspace_sid'],
workflow_sid=self._solution['workflow_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Taskrouter.V1.WorkflowRealTimeStatisticsContext {}>'.format(context)
class WorkflowRealTimeStatisticsInstance(InstanceResource):
def __init__(self, version, payload, workspace_sid, workflow_sid):
"""
Initialize the WorkflowRealTimeStatisticsInstance
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsInstance
"""
super(WorkflowRealTimeStatisticsInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'account_sid': payload.get('account_sid'),
'longest_task_waiting_age': deserialize.integer(payload.get('longest_task_waiting_age')),
'longest_task_waiting_sid': payload.get('longest_task_waiting_sid'),
'tasks_by_priority': payload.get('tasks_by_priority'),
'tasks_by_status': payload.get('tasks_by_status'),
'total_tasks': deserialize.integer(payload.get('total_tasks')),
'workflow_sid': payload.get('workflow_sid'),
'workspace_sid': payload.get('workspace_sid'),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: WorkflowRealTimeStatisticsContext for this WorkflowRealTimeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext
"""
if self._context is None:
self._context = WorkflowRealTimeStatisticsContext(
self._version,
workspace_sid=self._solution['workspace_sid'],
workflow_sid=self._solution['workflow_sid'],
)
return self._context
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def longest_task_waiting_age(self):
"""
:returns: The age of the longest waiting Task
:rtype: unicode
"""
return self._properties['longest_task_waiting_age']
@property
def longest_task_waiting_sid(self):
"""
:returns: The SID of the longest waiting Task
:rtype: unicode
"""
return self._properties['longest_task_waiting_sid']
@property
def tasks_by_priority(self):
"""
:returns: The number of Tasks by priority
:rtype: dict
"""
return self._properties['tasks_by_priority']
@property
def tasks_by_status(self):
"""
:returns: The number of Tasks by their current status
:rtype: dict
"""
return self._properties['tasks_by_status']
@property
def total_tasks(self):
"""
:returns: The total number of Tasks
:rtype: unicode
"""
return self._properties['total_tasks']
@property
def workflow_sid(self):
"""
:returns: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value
:rtype: unicode
"""
return self._properties['workflow_sid']
@property
def workspace_sid(self):
"""
:returns: The SID of the Workspace that contains the Workflow.
:rtype: unicode
"""
return self._properties['workspace_sid']
@property
def url(self):
"""
:returns: The absolute URL of the Workflow statistics resource
:rtype: unicode
"""
return self._properties['url']
def fetch(self, task_channel=values.unset):
"""
Fetch the WorkflowRealTimeStatisticsInstance
:param unicode task_channel: Only calculate real-time statistics on this TaskChannel
:returns: The fetched WorkflowRealTimeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsInstance
"""
return self._proxy.fetch(task_channel=task_channel, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Taskrouter.V1.WorkflowRealTimeStatisticsInstance {}>'.format(context)
| mit | fdb0edd2be266a124b8c983317a2ddc1 | 36.692053 | 127 | 0.661337 | 4.467425 | false | false | false | false |
twilio/twilio-python | twilio/rest/serverless/v1/service/function/__init__.py | 1 | 15989 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
from twilio.rest.serverless.v1.service.function.function_version import FunctionVersionList
class FunctionList(ListResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, service_sid):
"""
Initialize the FunctionList
:param Version version: Version that contains the resource
:param service_sid: The SID of the Service that the Function resource is associated with
:returns: twilio.rest.serverless.v1.service.function.FunctionList
:rtype: twilio.rest.serverless.v1.service.function.FunctionList
"""
super(FunctionList, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, }
self._uri = '/Services/{service_sid}/Functions'.format(**self._solution)
def stream(self, limit=None, page_size=None):
"""
Streams FunctionInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.serverless.v1.service.function.FunctionInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, limit=None, page_size=None):
"""
Lists FunctionInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.serverless.v1.service.function.FunctionInstance]
"""
return list(self.stream(limit=limit, page_size=page_size, ))
def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of FunctionInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of FunctionInstance
:rtype: twilio.rest.serverless.v1.service.function.FunctionPage
"""
data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })
response = self._version.page(method='GET', uri=self._uri, params=data, )
return FunctionPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of FunctionInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of FunctionInstance
:rtype: twilio.rest.serverless.v1.service.function.FunctionPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return FunctionPage(self._version, response, self._solution)
def create(self, friendly_name):
"""
Create the FunctionInstance
:param unicode friendly_name: A string to describe the Function resource
:returns: The created FunctionInstance
:rtype: twilio.rest.serverless.v1.service.function.FunctionInstance
"""
data = values.of({'FriendlyName': friendly_name, })
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return FunctionInstance(self._version, payload, service_sid=self._solution['service_sid'], )
def get(self, sid):
"""
Constructs a FunctionContext
:param sid: The SID of the Function resource to fetch
:returns: twilio.rest.serverless.v1.service.function.FunctionContext
:rtype: twilio.rest.serverless.v1.service.function.FunctionContext
"""
return FunctionContext(self._version, service_sid=self._solution['service_sid'], sid=sid, )
def __call__(self, sid):
"""
Constructs a FunctionContext
:param sid: The SID of the Function resource to fetch
:returns: twilio.rest.serverless.v1.service.function.FunctionContext
:rtype: twilio.rest.serverless.v1.service.function.FunctionContext
"""
return FunctionContext(self._version, service_sid=self._solution['service_sid'], sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Serverless.V1.FunctionList>'
class FunctionPage(Page):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, response, solution):
"""
Initialize the FunctionPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param service_sid: The SID of the Service that the Function resource is associated with
:returns: twilio.rest.serverless.v1.service.function.FunctionPage
:rtype: twilio.rest.serverless.v1.service.function.FunctionPage
"""
super(FunctionPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of FunctionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.serverless.v1.service.function.FunctionInstance
:rtype: twilio.rest.serverless.v1.service.function.FunctionInstance
"""
return FunctionInstance(self._version, payload, service_sid=self._solution['service_sid'], )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Serverless.V1.FunctionPage>'
class FunctionContext(InstanceContext):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, service_sid, sid):
"""
Initialize the FunctionContext
:param Version version: Version that contains the resource
:param service_sid: The SID of the Service to fetch the Function resource from
:param sid: The SID of the Function resource to fetch
:returns: twilio.rest.serverless.v1.service.function.FunctionContext
:rtype: twilio.rest.serverless.v1.service.function.FunctionContext
"""
super(FunctionContext, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, 'sid': sid, }
self._uri = '/Services/{service_sid}/Functions/{sid}'.format(**self._solution)
# Dependents
self._function_versions = None
def fetch(self):
"""
Fetch the FunctionInstance
:returns: The fetched FunctionInstance
:rtype: twilio.rest.serverless.v1.service.function.FunctionInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return FunctionInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
sid=self._solution['sid'],
)
def delete(self):
"""
Deletes the FunctionInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def update(self, friendly_name):
"""
Update the FunctionInstance
:param unicode friendly_name: A string to describe the Function resource
:returns: The updated FunctionInstance
:rtype: twilio.rest.serverless.v1.service.function.FunctionInstance
"""
data = values.of({'FriendlyName': friendly_name, })
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return FunctionInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
sid=self._solution['sid'],
)
@property
def function_versions(self):
"""
Access the function_versions
:returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList
:rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList
"""
if self._function_versions is None:
self._function_versions = FunctionVersionList(
self._version,
service_sid=self._solution['service_sid'],
function_sid=self._solution['sid'],
)
return self._function_versions
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Serverless.V1.FunctionContext {}>'.format(context)
class FunctionInstance(InstanceResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, payload, service_sid, sid=None):
"""
Initialize the FunctionInstance
:returns: twilio.rest.serverless.v1.service.function.FunctionInstance
:rtype: twilio.rest.serverless.v1.service.function.FunctionInstance
"""
super(FunctionInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'account_sid': payload.get('account_sid'),
'service_sid': payload.get('service_sid'),
'friendly_name': payload.get('friendly_name'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'url': payload.get('url'),
'links': payload.get('links'),
}
# Context
self._context = None
self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: FunctionContext for this FunctionInstance
:rtype: twilio.rest.serverless.v1.service.function.FunctionContext
"""
if self._context is None:
self._context = FunctionContext(
self._version,
service_sid=self._solution['service_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the Function resource
:rtype: unicode
"""
return self._properties['sid']
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the Function resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def service_sid(self):
"""
:returns: The SID of the Service that the Function resource is associated with
:rtype: unicode
"""
return self._properties['service_sid']
@property
def friendly_name(self):
"""
:returns: The string that you assigned to describe the Function resource
:rtype: unicode
"""
return self._properties['friendly_name']
@property
def date_created(self):
"""
:returns: The ISO 8601 date and time in GMT when the Function resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The ISO 8601 date and time in GMT when the Function resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def url(self):
"""
:returns: The absolute URL of the Function resource
:rtype: unicode
"""
return self._properties['url']
@property
def links(self):
"""
:returns: The URLs of nested resources of the Function resource
:rtype: unicode
"""
return self._properties['links']
def fetch(self):
"""
Fetch the FunctionInstance
:returns: The fetched FunctionInstance
:rtype: twilio.rest.serverless.v1.service.function.FunctionInstance
"""
return self._proxy.fetch()
def delete(self):
"""
Deletes the FunctionInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def update(self, friendly_name):
"""
Update the FunctionInstance
:param unicode friendly_name: A string to describe the Function resource
:returns: The updated FunctionInstance
:rtype: twilio.rest.serverless.v1.service.function.FunctionInstance
"""
return self._proxy.update(friendly_name, )
@property
def function_versions(self):
"""
Access the function_versions
:returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList
:rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList
"""
return self._proxy.function_versions
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Serverless.V1.FunctionInstance {}>'.format(context)
| mit | c74c58535548a435ca770d8e278c5c01 | 34.063596 | 100 | 0.625618 | 4.468698 | false | false | false | false |
twilio/twilio-python | tests/integration/api/v2010/account/test_key.py | 1 | 5819 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class KeyTestCase(IntegrationTestCase):
def test_fetch_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.keys("SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()
self.holodeck.assert_has_request(Request(
'get',
'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys/SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json',
))
def test_fetch_response(self):
self.holodeck.mock(Response(
200,
'''
{
"sid": "SKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"friendly_name": "foo",
"date_created": "Mon, 13 Jun 2016 22:50:08 +0000",
"date_updated": "Mon, 13 Jun 2016 22:50:08 +0000"
}
'''
))
actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.keys("SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()
self.assertIsNotNone(actual)
def test_update_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.keys("SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update()
self.holodeck.assert_has_request(Request(
'post',
'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys/SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json',
))
def test_update_response(self):
self.holodeck.mock(Response(
200,
'''
{
"sid": "SKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"friendly_name": "foo",
"date_created": "Mon, 13 Jun 2016 22:50:08 +0000",
"date_updated": "Mon, 13 Jun 2016 22:50:08 +0000"
}
'''
))
actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.keys("SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update()
self.assertIsNotNone(actual)
def test_delete_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.keys("SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete()
self.holodeck.assert_has_request(Request(
'delete',
'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys/SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json',
))
def test_delete_response(self):
self.holodeck.mock(Response(
204,
None,
))
actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.keys("SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete()
self.assertTrue(actual)
def test_list_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.keys.list()
self.holodeck.assert_has_request(Request(
'get',
'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys.json',
))
def test_read_full_response(self):
self.holodeck.mock(Response(
200,
'''
{
"keys": [
{
"sid": "SKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"friendly_name": "foo",
"date_created": "Mon, 13 Jun 2016 22:50:08 +0000",
"date_updated": "Mon, 13 Jun 2016 22:50:08 +0000"
}
],
"first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys.json?PageSize=50&Page=0",
"end": 0,
"previous_page_uri": null,
"uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys.json?PageSize=50&Page=0",
"page_size": 50,
"start": 0,
"next_page_uri": null,
"page": 0
}
'''
))
actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.keys.list()
self.assertIsNotNone(actual)
def test_read_empty_response(self):
self.holodeck.mock(Response(
200,
'''
{
"keys": [],
"first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys.json?PageSize=50&Page=0",
"end": 0,
"previous_page_uri": null,
"uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys.json?PageSize=50&Page=0",
"page_size": 50,
"start": 0,
"next_page_uri": null,
"page": 0
}
'''
))
actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.keys.list()
self.assertIsNotNone(actual)
| mit | c06b71e6be6541ef4fa233c3537d586f | 34.699387 | 137 | 0.543392 | 4.465848 | false | true | false | false |
twilio/twilio-python | twilio/rest/serverless/v1/service/environment/log.py | 1 | 16480 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class LogList(ListResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, service_sid, environment_sid):
"""
Initialize the LogList
:param Version version: Version that contains the resource
:param service_sid: The SID of the Service that the Log resource is associated with
:param environment_sid: The SID of the environment in which the log occurred
:returns: twilio.rest.serverless.v1.service.environment.log.LogList
:rtype: twilio.rest.serverless.v1.service.environment.log.LogList
"""
super(LogList, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, 'environment_sid': environment_sid, }
self._uri = '/Services/{service_sid}/Environments/{environment_sid}/Logs'.format(**self._solution)
def stream(self, function_sid=values.unset, start_date=values.unset,
end_date=values.unset, limit=None, page_size=None):
"""
Streams LogInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param unicode function_sid: The SID of the function whose invocation produced the Log resources to read
:param datetime start_date: The date and time after which the Log resources must have been created.
:param datetime end_date: The date and time before which the Log resource must have been created.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.serverless.v1.service.environment.log.LogInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(
function_sid=function_sid,
start_date=start_date,
end_date=end_date,
page_size=limits['page_size'],
)
return self._version.stream(page, limits['limit'])
def list(self, function_sid=values.unset, start_date=values.unset,
end_date=values.unset, limit=None, page_size=None):
"""
Lists LogInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param unicode function_sid: The SID of the function whose invocation produced the Log resources to read
:param datetime start_date: The date and time after which the Log resources must have been created.
:param datetime end_date: The date and time before which the Log resource must have been created.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.serverless.v1.service.environment.log.LogInstance]
"""
return list(self.stream(
function_sid=function_sid,
start_date=start_date,
end_date=end_date,
limit=limit,
page_size=page_size,
))
def page(self, function_sid=values.unset, start_date=values.unset,
end_date=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
"""
Retrieve a single page of LogInstance records from the API.
Request is executed immediately
:param unicode function_sid: The SID of the function whose invocation produced the Log resources to read
:param datetime start_date: The date and time after which the Log resources must have been created.
:param datetime end_date: The date and time before which the Log resource must have been created.
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of LogInstance
:rtype: twilio.rest.serverless.v1.service.environment.log.LogPage
"""
data = values.of({
'FunctionSid': function_sid,
'StartDate': serialize.iso8601_datetime(start_date),
'EndDate': serialize.iso8601_datetime(end_date),
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(method='GET', uri=self._uri, params=data, )
return LogPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of LogInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of LogInstance
:rtype: twilio.rest.serverless.v1.service.environment.log.LogPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return LogPage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a LogContext
:param sid: The SID that identifies the Log resource to fetch
:returns: twilio.rest.serverless.v1.service.environment.log.LogContext
:rtype: twilio.rest.serverless.v1.service.environment.log.LogContext
"""
return LogContext(
self._version,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
sid=sid,
)
def __call__(self, sid):
"""
Constructs a LogContext
:param sid: The SID that identifies the Log resource to fetch
:returns: twilio.rest.serverless.v1.service.environment.log.LogContext
:rtype: twilio.rest.serverless.v1.service.environment.log.LogContext
"""
return LogContext(
self._version,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
sid=sid,
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Serverless.V1.LogList>'
class LogPage(Page):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, response, solution):
"""
Initialize the LogPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param service_sid: The SID of the Service that the Log resource is associated with
:param environment_sid: The SID of the environment in which the log occurred
:returns: twilio.rest.serverless.v1.service.environment.log.LogPage
:rtype: twilio.rest.serverless.v1.service.environment.log.LogPage
"""
super(LogPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of LogInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.serverless.v1.service.environment.log.LogInstance
:rtype: twilio.rest.serverless.v1.service.environment.log.LogInstance
"""
return LogInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Serverless.V1.LogPage>'
class LogContext(InstanceContext):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, service_sid, environment_sid, sid):
"""
Initialize the LogContext
:param Version version: Version that contains the resource
:param service_sid: The SID of the Service to fetch the Log resource from
:param environment_sid: The SID of the environment with the Log resource to fetch
:param sid: The SID that identifies the Log resource to fetch
:returns: twilio.rest.serverless.v1.service.environment.log.LogContext
:rtype: twilio.rest.serverless.v1.service.environment.log.LogContext
"""
super(LogContext, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, 'environment_sid': environment_sid, 'sid': sid, }
self._uri = '/Services/{service_sid}/Environments/{environment_sid}/Logs/{sid}'.format(**self._solution)
def fetch(self):
"""
Fetch the LogInstance
:returns: The fetched LogInstance
:rtype: twilio.rest.serverless.v1.service.environment.log.LogInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return LogInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
sid=self._solution['sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Serverless.V1.LogContext {}>'.format(context)
class LogInstance(InstanceResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
class Level(object):
INFO = "info"
WARN = "warn"
ERROR = "error"
def __init__(self, version, payload, service_sid, environment_sid, sid=None):
"""
Initialize the LogInstance
:returns: twilio.rest.serverless.v1.service.environment.log.LogInstance
:rtype: twilio.rest.serverless.v1.service.environment.log.LogInstance
"""
super(LogInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'account_sid': payload.get('account_sid'),
'service_sid': payload.get('service_sid'),
'environment_sid': payload.get('environment_sid'),
'build_sid': payload.get('build_sid'),
'deployment_sid': payload.get('deployment_sid'),
'function_sid': payload.get('function_sid'),
'request_sid': payload.get('request_sid'),
'level': payload.get('level'),
'message': payload.get('message'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {
'service_sid': service_sid,
'environment_sid': environment_sid,
'sid': sid or self._properties['sid'],
}
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: LogContext for this LogInstance
:rtype: twilio.rest.serverless.v1.service.environment.log.LogContext
"""
if self._context is None:
self._context = LogContext(
self._version,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the Log resource
:rtype: unicode
"""
return self._properties['sid']
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the Log resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def service_sid(self):
"""
:returns: The SID of the Service that the Log resource is associated with
:rtype: unicode
"""
return self._properties['service_sid']
@property
def environment_sid(self):
"""
:returns: The SID of the environment in which the log occurred
:rtype: unicode
"""
return self._properties['environment_sid']
@property
def build_sid(self):
"""
:returns: The SID of the build that corresponds to the log
:rtype: unicode
"""
return self._properties['build_sid']
@property
def deployment_sid(self):
"""
:returns: The SID of the deployment that corresponds to the log
:rtype: unicode
"""
return self._properties['deployment_sid']
@property
def function_sid(self):
"""
:returns: The SID of the function whose invocation produced the log
:rtype: unicode
"""
return self._properties['function_sid']
@property
def request_sid(self):
"""
:returns: The SID of the request associated with the log
:rtype: unicode
"""
return self._properties['request_sid']
@property
def level(self):
"""
:returns: The log level
:rtype: LogInstance.Level
"""
return self._properties['level']
@property
def message(self):
"""
:returns: The log message
:rtype: unicode
"""
return self._properties['message']
@property
def date_created(self):
"""
:returns: The ISO 8601 date and time in GMT when the Log resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def url(self):
"""
:returns: The absolute URL of the Log resource
:rtype: unicode
"""
return self._properties['url']
def fetch(self):
"""
Fetch the LogInstance
:returns: The fetched LogInstance
:rtype: twilio.rest.serverless.v1.service.environment.log.LogInstance
"""
return self._proxy.fetch()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Serverless.V1.LogInstance {}>'.format(context)
| mit | 7827c00dd2464ad1f2fda2539db9907a | 34.982533 | 112 | 0.612439 | 4.399359 | false | false | false | false |
twilio/twilio-python | tests/integration/conversations/v1/test_participant_conversation.py | 1 | 6818 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class ParticipantConversationTestCase(IntegrationTestCase):
def test_list_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.conversations.v1.participant_conversations.list()
self.holodeck.assert_has_request(Request(
'get',
'https://conversations.twilio.com/v1/ParticipantConversations',
))
def test_read_empty_response(self):
self.holodeck.mock(Response(
200,
'''
{
"conversations": [],
"meta": {
"page": 0,
"page_size": 50,
"first_page_url": "https://conversations.twilio.com/v1/ParticipantConversations?Identity=identity&PageSize=50&Page=0",
"previous_page_url": null,
"url": "https://conversations.twilio.com/v1/ParticipantConversations?Identity=identity&PageSize=50&Page=0",
"next_page_url": null,
"key": "conversations"
}
}
'''
))
actual = self.client.conversations.v1.participant_conversations.list()
self.assertIsNotNone(actual)
def test_read_full_by_identity_response(self):
self.holodeck.mock(Response(
200,
'''
{
"conversations": [
{
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"chat_service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"participant_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"conversation_friendly_name": "friendly_name",
"conversation_state": "inactive",
"conversation_timers": {
"date_inactive": "2015-12-16T22:19:38Z",
"date_closed": "2015-12-16T22:28:38Z"
},
"conversation_attributes": "{}",
"conversation_date_created": "2015-07-30T20:00:00Z",
"conversation_date_updated": "2015-07-30T20:00:00Z",
"conversation_created_by": "created_by",
"conversation_unique_name": "unique_name",
"participant_user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"participant_identity": "identity",
"participant_messaging_binding": null,
"links": {
"participant": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"conversation": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
}
],
"meta": {
"page": 0,
"page_size": 50,
"first_page_url": "https://conversations.twilio.com/v1/ParticipantConversations?Identity=identity&PageSize=50&Page=0",
"previous_page_url": null,
"url": "https://conversations.twilio.com/v1/ParticipantConversations?Identity=identity&PageSize=50&Page=0",
"next_page_url": null,
"key": "conversations"
}
}
'''
))
actual = self.client.conversations.v1.participant_conversations.list()
self.assertIsNotNone(actual)
def test_read_full_by_address_response(self):
self.holodeck.mock(Response(
200,
'''
{
"conversations": [
{
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"chat_service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"participant_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"conversation_friendly_name": "friendly_name",
"conversation_state": "inactive",
"conversation_timers": {
"date_inactive": "2015-12-16T22:19:38Z",
"date_closed": "2015-12-16T22:28:38Z"
},
"conversation_attributes": "{}",
"conversation_date_created": "2015-07-30T20:00:00Z",
"conversation_date_updated": "2015-07-30T20:00:00Z",
"conversation_created_by": "created_by",
"conversation_unique_name": "unique_name",
"participant_user_sid": null,
"participant_identity": null,
"participant_messaging_binding": {
"address": "+375255555555",
"proxy_address": "+12345678910",
"type": "sms",
"level": null,
"name": null,
"projected_address": null
},
"links": {
"participant": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"conversation": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
}
],
"meta": {
"page": 0,
"page_size": 50,
"first_page_url": "https://conversations.twilio.com/v1/ParticipantConversations?Address=%2B375255555555&PageSize=50&Page=0",
"previous_page_url": null,
"url": "https://conversations.twilio.com/v1/ParticipantConversations?Address=%2B375255555555&PageSize=50&Page=0",
"next_page_url": null,
"key": "conversations"
}
}
'''
))
actual = self.client.conversations.v1.participant_conversations.list()
self.assertIsNotNone(actual)
| mit | 4039f0f1a8f91b351771f05e1d1d99d5 | 43.855263 | 178 | 0.497507 | 4.566644 | false | true | false | false |
twilio/twilio-python | twilio/base/serialize.py | 1 | 2041 | import datetime
import json
from twilio.base import values
def iso8601_date(d):
"""
Return a string representation of a date that the Twilio API understands
Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date
"""
if d == values.unset:
return d
elif isinstance(d, datetime.datetime):
return str(d.date())
elif isinstance(d, datetime.date):
return str(d)
elif isinstance(d, str):
return d
def iso8601_datetime(d):
"""
Return a string representation of a date that the Twilio API understands
Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date
"""
if d == values.unset:
return d
elif isinstance(d, datetime.datetime) or isinstance(d, datetime.date):
return d.strftime('%Y-%m-%dT%H:%M:%SZ')
elif isinstance(d, str):
return d
def prefixed_collapsible_map(m, prefix):
"""
Return a dict of params corresponding to those in m with the added prefix
"""
if m == values.unset:
return {}
def flatten_dict(d, result=None, prv_keys=None):
if result is None:
result = {}
if prv_keys is None:
prv_keys = []
for k, v in d.items():
if isinstance(v, dict):
flatten_dict(v, result, prv_keys + [k])
else:
result['.'.join(prv_keys + [k])] = v
return result
if isinstance(m, dict):
flattened = flatten_dict(m)
return {'{}.{}'.format(prefix, k): v for k, v in flattened.items()}
return {}
def object(obj):
"""
Return a jsonified string represenation of obj if obj is jsonifiable else
return obj untouched
"""
if isinstance(obj, dict) or isinstance(obj, list):
return json.dumps(obj)
return obj
def map(lst, serialize_func):
"""
Applies serialize_func to every element in lst
"""
if not isinstance(lst, list):
return lst
return [serialize_func(e) for e in lst]
| mit | 0093c4c28ed9864c143f2d215073fa0e | 23.890244 | 78 | 0.595296 | 3.822097 | false | false | false | false |
twilio/twilio-python | twilio/rest/events/v1/subscription/subscribed_event.py | 1 | 14996 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class SubscribedEventList(ListResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, subscription_sid):
"""
Initialize the SubscribedEventList
:param Version version: Version that contains the resource
:param subscription_sid: Subscription SID.
:returns: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventList
:rtype: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventList
"""
super(SubscribedEventList, self).__init__(version)
# Path Solution
self._solution = {'subscription_sid': subscription_sid, }
self._uri = '/Subscriptions/{subscription_sid}/SubscribedEvents'.format(**self._solution)
def stream(self, limit=None, page_size=None):
"""
Streams SubscribedEventInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, limit=None, page_size=None):
"""
Lists SubscribedEventInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventInstance]
"""
return list(self.stream(limit=limit, page_size=page_size, ))
def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of SubscribedEventInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of SubscribedEventInstance
:rtype: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventPage
"""
data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })
response = self._version.page(method='GET', uri=self._uri, params=data, )
return SubscribedEventPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of SubscribedEventInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of SubscribedEventInstance
:rtype: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return SubscribedEventPage(self._version, response, self._solution)
def create(self, type, schema_version=values.unset):
"""
Create the SubscribedEventInstance
:param unicode type: Type of event being subscribed to.
:param unicode schema_version: The schema version that the subscription should use.
:returns: The created SubscribedEventInstance
:rtype: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventInstance
"""
data = values.of({'Type': type, 'SchemaVersion': schema_version, })
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return SubscribedEventInstance(
self._version,
payload,
subscription_sid=self._solution['subscription_sid'],
)
def get(self, type):
"""
Constructs a SubscribedEventContext
:param type: Type of event being subscribed to.
:returns: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventContext
:rtype: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventContext
"""
return SubscribedEventContext(
self._version,
subscription_sid=self._solution['subscription_sid'],
type=type,
)
def __call__(self, type):
"""
Constructs a SubscribedEventContext
:param type: Type of event being subscribed to.
:returns: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventContext
:rtype: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventContext
"""
return SubscribedEventContext(
self._version,
subscription_sid=self._solution['subscription_sid'],
type=type,
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Events.V1.SubscribedEventList>'
class SubscribedEventPage(Page):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, response, solution):
"""
Initialize the SubscribedEventPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param subscription_sid: Subscription SID.
:returns: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventPage
:rtype: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventPage
"""
super(SubscribedEventPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of SubscribedEventInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventInstance
:rtype: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventInstance
"""
return SubscribedEventInstance(
self._version,
payload,
subscription_sid=self._solution['subscription_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Events.V1.SubscribedEventPage>'
class SubscribedEventContext(InstanceContext):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, subscription_sid, type):
"""
Initialize the SubscribedEventContext
:param Version version: Version that contains the resource
:param subscription_sid: Subscription SID.
:param type: Type of event being subscribed to.
:returns: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventContext
:rtype: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventContext
"""
super(SubscribedEventContext, self).__init__(version)
# Path Solution
self._solution = {'subscription_sid': subscription_sid, 'type': type, }
self._uri = '/Subscriptions/{subscription_sid}/SubscribedEvents/{type}'.format(**self._solution)
def fetch(self):
"""
Fetch the SubscribedEventInstance
:returns: The fetched SubscribedEventInstance
:rtype: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return SubscribedEventInstance(
self._version,
payload,
subscription_sid=self._solution['subscription_sid'],
type=self._solution['type'],
)
def update(self, schema_version=values.unset):
"""
Update the SubscribedEventInstance
:param unicode schema_version: The schema version that the subscription should use.
:returns: The updated SubscribedEventInstance
:rtype: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventInstance
"""
data = values.of({'SchemaVersion': schema_version, })
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return SubscribedEventInstance(
self._version,
payload,
subscription_sid=self._solution['subscription_sid'],
type=self._solution['type'],
)
def delete(self):
"""
Deletes the SubscribedEventInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Events.V1.SubscribedEventContext {}>'.format(context)
class SubscribedEventInstance(InstanceResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, payload, subscription_sid, type=None):
"""
Initialize the SubscribedEventInstance
:returns: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventInstance
:rtype: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventInstance
"""
super(SubscribedEventInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'account_sid': payload.get('account_sid'),
'type': payload.get('type'),
'schema_version': deserialize.integer(payload.get('schema_version')),
'subscription_sid': payload.get('subscription_sid'),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {'subscription_sid': subscription_sid, 'type': type or self._properties['type'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SubscribedEventContext for this SubscribedEventInstance
:rtype: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventContext
"""
if self._context is None:
self._context = SubscribedEventContext(
self._version,
subscription_sid=self._solution['subscription_sid'],
type=self._solution['type'],
)
return self._context
@property
def account_sid(self):
"""
:returns: Account SID.
:rtype: unicode
"""
return self._properties['account_sid']
@property
def type(self):
"""
:returns: Type of event being subscribed to.
:rtype: unicode
"""
return self._properties['type']
@property
def schema_version(self):
"""
:returns: The schema version that the subscription should use.
:rtype: unicode
"""
return self._properties['schema_version']
@property
def subscription_sid(self):
"""
:returns: Subscription SID.
:rtype: unicode
"""
return self._properties['subscription_sid']
@property
def url(self):
"""
:returns: The URL of this resource.
:rtype: unicode
"""
return self._properties['url']
def fetch(self):
"""
Fetch the SubscribedEventInstance
:returns: The fetched SubscribedEventInstance
:rtype: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventInstance
"""
return self._proxy.fetch()
def update(self, schema_version=values.unset):
"""
Update the SubscribedEventInstance
:param unicode schema_version: The schema version that the subscription should use.
:returns: The updated SubscribedEventInstance
:rtype: twilio.rest.events.v1.subscription.subscribed_event.SubscribedEventInstance
"""
return self._proxy.update(schema_version=schema_version, )
def delete(self):
"""
Deletes the SubscribedEventInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Events.V1.SubscribedEventInstance {}>'.format(context)
| mit | dc52a470561f3dc1e676c528ad04dfd7 | 35.048077 | 107 | 0.636503 | 4.522316 | false | false | false | false |
twilio/twilio-python | twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py | 1 | 17374 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class WorkflowCumulativeStatisticsList(ListResource):
def __init__(self, version, workspace_sid, workflow_sid):
"""
Initialize the WorkflowCumulativeStatisticsList
:param Version version: Version that contains the resource
:param workspace_sid: The SID of the Workspace that contains the Workflow.
:param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsList
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsList
"""
super(WorkflowCumulativeStatisticsList, self).__init__(version)
# Path Solution
self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, }
def get(self):
"""
Constructs a WorkflowCumulativeStatisticsContext
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext
"""
return WorkflowCumulativeStatisticsContext(
self._version,
workspace_sid=self._solution['workspace_sid'],
workflow_sid=self._solution['workflow_sid'],
)
def __call__(self):
"""
Constructs a WorkflowCumulativeStatisticsContext
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext
"""
return WorkflowCumulativeStatisticsContext(
self._version,
workspace_sid=self._solution['workspace_sid'],
workflow_sid=self._solution['workflow_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Taskrouter.V1.WorkflowCumulativeStatisticsList>'
class WorkflowCumulativeStatisticsPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the WorkflowCumulativeStatisticsPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param workspace_sid: The SID of the Workspace that contains the Workflow.
:param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsPage
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsPage
"""
super(WorkflowCumulativeStatisticsPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of WorkflowCumulativeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance
"""
return WorkflowCumulativeStatisticsInstance(
self._version,
payload,
workspace_sid=self._solution['workspace_sid'],
workflow_sid=self._solution['workflow_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Taskrouter.V1.WorkflowCumulativeStatisticsPage>'
class WorkflowCumulativeStatisticsContext(InstanceContext):
def __init__(self, version, workspace_sid, workflow_sid):
"""
Initialize the WorkflowCumulativeStatisticsContext
:param Version version: Version that contains the resource
:param workspace_sid: The SID of the Workspace with the resource to fetch
:param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext
"""
super(WorkflowCumulativeStatisticsContext, self).__init__(version)
# Path Solution
self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, }
self._uri = '/Workspaces/{workspace_sid}/Workflows/{workflow_sid}/CumulativeStatistics'.format(**self._solution)
def fetch(self, end_date=values.unset, minutes=values.unset,
start_date=values.unset, task_channel=values.unset,
split_by_wait_time=values.unset):
"""
Fetch the WorkflowCumulativeStatisticsInstance
:param datetime end_date: Only include usage that occurred on or before this date
:param unicode minutes: Only calculate statistics since this many minutes in the past
:param datetime start_date: Only calculate statistics from on or after this date
:param unicode task_channel: Only calculate cumulative statistics on this TaskChannel
:param unicode split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on
:returns: The fetched WorkflowCumulativeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance
"""
data = values.of({
'EndDate': serialize.iso8601_datetime(end_date),
'Minutes': minutes,
'StartDate': serialize.iso8601_datetime(start_date),
'TaskChannel': task_channel,
'SplitByWaitTime': split_by_wait_time,
})
payload = self._version.fetch(method='GET', uri=self._uri, params=data, )
return WorkflowCumulativeStatisticsInstance(
self._version,
payload,
workspace_sid=self._solution['workspace_sid'],
workflow_sid=self._solution['workflow_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Taskrouter.V1.WorkflowCumulativeStatisticsContext {}>'.format(context)
class WorkflowCumulativeStatisticsInstance(InstanceResource):
def __init__(self, version, payload, workspace_sid, workflow_sid):
"""
Initialize the WorkflowCumulativeStatisticsInstance
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance
"""
super(WorkflowCumulativeStatisticsInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'account_sid': payload.get('account_sid'),
'avg_task_acceptance_time': deserialize.integer(payload.get('avg_task_acceptance_time')),
'start_time': deserialize.iso8601_datetime(payload.get('start_time')),
'end_time': deserialize.iso8601_datetime(payload.get('end_time')),
'reservations_created': deserialize.integer(payload.get('reservations_created')),
'reservations_accepted': deserialize.integer(payload.get('reservations_accepted')),
'reservations_rejected': deserialize.integer(payload.get('reservations_rejected')),
'reservations_timed_out': deserialize.integer(payload.get('reservations_timed_out')),
'reservations_canceled': deserialize.integer(payload.get('reservations_canceled')),
'reservations_rescinded': deserialize.integer(payload.get('reservations_rescinded')),
'split_by_wait_time': payload.get('split_by_wait_time'),
'wait_duration_until_accepted': payload.get('wait_duration_until_accepted'),
'wait_duration_until_canceled': payload.get('wait_duration_until_canceled'),
'tasks_canceled': deserialize.integer(payload.get('tasks_canceled')),
'tasks_completed': deserialize.integer(payload.get('tasks_completed')),
'tasks_entered': deserialize.integer(payload.get('tasks_entered')),
'tasks_deleted': deserialize.integer(payload.get('tasks_deleted')),
'tasks_moved': deserialize.integer(payload.get('tasks_moved')),
'tasks_timed_out_in_workflow': deserialize.integer(payload.get('tasks_timed_out_in_workflow')),
'workflow_sid': payload.get('workflow_sid'),
'workspace_sid': payload.get('workspace_sid'),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: WorkflowCumulativeStatisticsContext for this WorkflowCumulativeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext
"""
if self._context is None:
self._context = WorkflowCumulativeStatisticsContext(
self._version,
workspace_sid=self._solution['workspace_sid'],
workflow_sid=self._solution['workflow_sid'],
)
return self._context
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def avg_task_acceptance_time(self):
"""
:returns: The average time in seconds between Task creation and acceptance
:rtype: unicode
"""
return self._properties['avg_task_acceptance_time']
@property
def start_time(self):
"""
:returns: The beginning of the interval during which these statistics were calculated
:rtype: datetime
"""
return self._properties['start_time']
@property
def end_time(self):
"""
:returns: The end of the interval during which these statistics were calculated
:rtype: datetime
"""
return self._properties['end_time']
@property
def reservations_created(self):
"""
:returns: The total number of Reservations that were created for Workers
:rtype: unicode
"""
return self._properties['reservations_created']
@property
def reservations_accepted(self):
"""
:returns: The total number of Reservations accepted by Workers
:rtype: unicode
"""
return self._properties['reservations_accepted']
@property
def reservations_rejected(self):
"""
:returns: The total number of Reservations that were rejected
:rtype: unicode
"""
return self._properties['reservations_rejected']
@property
def reservations_timed_out(self):
"""
:returns: The total number of Reservations that were timed out
:rtype: unicode
"""
return self._properties['reservations_timed_out']
@property
def reservations_canceled(self):
"""
:returns: The total number of Reservations that were canceled
:rtype: unicode
"""
return self._properties['reservations_canceled']
@property
def reservations_rescinded(self):
"""
:returns: The total number of Reservations that were rescinded
:rtype: unicode
"""
return self._properties['reservations_rescinded']
@property
def split_by_wait_time(self):
"""
:returns: A list of objects that describe the Tasks canceled and reservations accepted above and below the specified thresholds
:rtype: dict
"""
return self._properties['split_by_wait_time']
@property
def wait_duration_until_accepted(self):
"""
:returns: The wait duration statistics for Tasks that were accepted
:rtype: dict
"""
return self._properties['wait_duration_until_accepted']
@property
def wait_duration_until_canceled(self):
"""
:returns: The wait duration statistics for Tasks that were canceled
:rtype: dict
"""
return self._properties['wait_duration_until_canceled']
@property
def tasks_canceled(self):
"""
:returns: The total number of Tasks that were canceled
:rtype: unicode
"""
return self._properties['tasks_canceled']
@property
def tasks_completed(self):
"""
:returns: The total number of Tasks that were completed
:rtype: unicode
"""
return self._properties['tasks_completed']
@property
def tasks_entered(self):
"""
:returns: The total number of Tasks that entered the Workflow
:rtype: unicode
"""
return self._properties['tasks_entered']
@property
def tasks_deleted(self):
"""
:returns: The total number of Tasks that were deleted
:rtype: unicode
"""
return self._properties['tasks_deleted']
@property
def tasks_moved(self):
"""
:returns: The total number of Tasks that were moved from one queue to another
:rtype: unicode
"""
return self._properties['tasks_moved']
@property
def tasks_timed_out_in_workflow(self):
"""
:returns: The total number of Tasks that were timed out of their Workflows
:rtype: unicode
"""
return self._properties['tasks_timed_out_in_workflow']
@property
def workflow_sid(self):
"""
:returns: Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value
:rtype: unicode
"""
return self._properties['workflow_sid']
@property
def workspace_sid(self):
"""
:returns: The SID of the Workspace that contains the Workflow.
:rtype: unicode
"""
return self._properties['workspace_sid']
@property
def url(self):
"""
:returns: The absolute URL of the Workflow statistics resource
:rtype: unicode
"""
return self._properties['url']
def fetch(self, end_date=values.unset, minutes=values.unset,
start_date=values.unset, task_channel=values.unset,
split_by_wait_time=values.unset):
"""
Fetch the WorkflowCumulativeStatisticsInstance
:param datetime end_date: Only include usage that occurred on or before this date
:param unicode minutes: Only calculate statistics since this many minutes in the past
:param datetime start_date: Only calculate statistics from on or after this date
:param unicode task_channel: Only calculate cumulative statistics on this TaskChannel
:param unicode split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on
:returns: The fetched WorkflowCumulativeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance
"""
return self._proxy.fetch(
end_date=end_date,
minutes=minutes,
start_date=start_date,
task_channel=task_channel,
split_by_wait_time=split_by_wait_time,
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Taskrouter.V1.WorkflowCumulativeStatisticsInstance {}>'.format(context)
| mit | 0b90fea6105c72b05d63e0ee0f861415 | 38.130631 | 145 | 0.658628 | 4.508044 | false | false | false | false |
twilio/twilio-python | twilio/rest/supersim/v1/network.py | 1 | 12106 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class NetworkList(ListResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version):
"""
Initialize the NetworkList
:param Version version: Version that contains the resource
:returns: twilio.rest.supersim.v1.network.NetworkList
:rtype: twilio.rest.supersim.v1.network.NetworkList
"""
super(NetworkList, self).__init__(version)
# Path Solution
self._solution = {}
self._uri = '/Networks'.format(**self._solution)
def stream(self, iso_country=values.unset, mcc=values.unset, mnc=values.unset,
limit=None, page_size=None):
"""
Streams NetworkInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param unicode iso_country: The ISO country code of the Network resources to read
:param unicode mcc: The MCC of Network resource identifiers to be read
:param unicode mnc: The MNC of Network resource identifiers to be read
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.supersim.v1.network.NetworkInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(iso_country=iso_country, mcc=mcc, mnc=mnc, page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, iso_country=values.unset, mcc=values.unset, mnc=values.unset,
limit=None, page_size=None):
"""
Lists NetworkInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param unicode iso_country: The ISO country code of the Network resources to read
:param unicode mcc: The MCC of Network resource identifiers to be read
:param unicode mnc: The MNC of Network resource identifiers to be read
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.supersim.v1.network.NetworkInstance]
"""
return list(self.stream(
iso_country=iso_country,
mcc=mcc,
mnc=mnc,
limit=limit,
page_size=page_size,
))
def page(self, iso_country=values.unset, mcc=values.unset, mnc=values.unset,
page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of NetworkInstance records from the API.
Request is executed immediately
:param unicode iso_country: The ISO country code of the Network resources to read
:param unicode mcc: The MCC of Network resource identifiers to be read
:param unicode mnc: The MNC of Network resource identifiers to be read
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of NetworkInstance
:rtype: twilio.rest.supersim.v1.network.NetworkPage
"""
data = values.of({
'IsoCountry': iso_country,
'Mcc': mcc,
'Mnc': mnc,
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(method='GET', uri=self._uri, params=data, )
return NetworkPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of NetworkInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of NetworkInstance
:rtype: twilio.rest.supersim.v1.network.NetworkPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return NetworkPage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a NetworkContext
:param sid: The SID of the Network resource to fetch
:returns: twilio.rest.supersim.v1.network.NetworkContext
:rtype: twilio.rest.supersim.v1.network.NetworkContext
"""
return NetworkContext(self._version, sid=sid, )
def __call__(self, sid):
"""
Constructs a NetworkContext
:param sid: The SID of the Network resource to fetch
:returns: twilio.rest.supersim.v1.network.NetworkContext
:rtype: twilio.rest.supersim.v1.network.NetworkContext
"""
return NetworkContext(self._version, sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Supersim.V1.NetworkList>'
class NetworkPage(Page):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, response, solution):
"""
Initialize the NetworkPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.supersim.v1.network.NetworkPage
:rtype: twilio.rest.supersim.v1.network.NetworkPage
"""
super(NetworkPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of NetworkInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.supersim.v1.network.NetworkInstance
:rtype: twilio.rest.supersim.v1.network.NetworkInstance
"""
return NetworkInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Supersim.V1.NetworkPage>'
class NetworkContext(InstanceContext):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, sid):
"""
Initialize the NetworkContext
:param Version version: Version that contains the resource
:param sid: The SID of the Network resource to fetch
:returns: twilio.rest.supersim.v1.network.NetworkContext
:rtype: twilio.rest.supersim.v1.network.NetworkContext
"""
super(NetworkContext, self).__init__(version)
# Path Solution
self._solution = {'sid': sid, }
self._uri = '/Networks/{sid}'.format(**self._solution)
def fetch(self):
"""
Fetch the NetworkInstance
:returns: The fetched NetworkInstance
:rtype: twilio.rest.supersim.v1.network.NetworkInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return NetworkInstance(self._version, payload, sid=self._solution['sid'], )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Supersim.V1.NetworkContext {}>'.format(context)
class NetworkInstance(InstanceResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, payload, sid=None):
"""
Initialize the NetworkInstance
:returns: twilio.rest.supersim.v1.network.NetworkInstance
:rtype: twilio.rest.supersim.v1.network.NetworkInstance
"""
super(NetworkInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'friendly_name': payload.get('friendly_name'),
'url': payload.get('url'),
'iso_country': payload.get('iso_country'),
'identifiers': payload.get('identifiers'),
}
# Context
self._context = None
self._solution = {'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: NetworkContext for this NetworkInstance
:rtype: twilio.rest.supersim.v1.network.NetworkContext
"""
if self._context is None:
self._context = NetworkContext(self._version, sid=self._solution['sid'], )
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def friendly_name(self):
"""
:returns: A human readable identifier of this resource
:rtype: unicode
"""
return self._properties['friendly_name']
@property
def url(self):
"""
:returns: The absolute URL of the Network resource
:rtype: unicode
"""
return self._properties['url']
@property
def iso_country(self):
"""
:returns: The ISO country code of the Network resource
:rtype: unicode
"""
return self._properties['iso_country']
@property
def identifiers(self):
"""
:returns: The MCC/MNCs included in the Network resource
:rtype: list[dict]
"""
return self._properties['identifiers']
def fetch(self):
"""
Fetch the NetworkInstance
:returns: The fetched NetworkInstance
:rtype: twilio.rest.supersim.v1.network.NetworkInstance
"""
return self._proxy.fetch()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Supersim.V1.NetworkInstance {}>'.format(context)
| mit | 646abdaddab4184f9efaffa88479bd1f | 33.887608 | 100 | 0.616554 | 4.3783 | false | false | false | false |
twilio/twilio-python | twilio/rest/api/v2010/account/address/__init__.py | 1 | 21916 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
from twilio.rest.api.v2010.account.address.dependent_phone_number import DependentPhoneNumberList
class AddressList(ListResource):
def __init__(self, version, account_sid):
"""
Initialize the AddressList
:param Version version: Version that contains the resource
:param account_sid: The SID of the Account that is responsible for the resource
:returns: twilio.rest.api.v2010.account.address.AddressList
:rtype: twilio.rest.api.v2010.account.address.AddressList
"""
super(AddressList, self).__init__(version)
# Path Solution
self._solution = {'account_sid': account_sid, }
self._uri = '/Accounts/{account_sid}/Addresses.json'.format(**self._solution)
def create(self, customer_name, street, city, region, postal_code, iso_country,
friendly_name=values.unset, emergency_enabled=values.unset,
auto_correct_address=values.unset):
"""
Create the AddressInstance
:param unicode customer_name: The name to associate with the new address
:param unicode street: The number and street address of the new address
:param unicode city: The city of the new address
:param unicode region: The state or region of the new address
:param unicode postal_code: The postal code of the new address
:param unicode iso_country: The ISO country code of the new address
:param unicode friendly_name: A string to describe the new resource
:param bool emergency_enabled: Whether to enable emergency calling on the new address
:param bool auto_correct_address: Whether we should automatically correct the address
:returns: The created AddressInstance
:rtype: twilio.rest.api.v2010.account.address.AddressInstance
"""
data = values.of({
'CustomerName': customer_name,
'Street': street,
'City': city,
'Region': region,
'PostalCode': postal_code,
'IsoCountry': iso_country,
'FriendlyName': friendly_name,
'EmergencyEnabled': emergency_enabled,
'AutoCorrectAddress': auto_correct_address,
})
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return AddressInstance(self._version, payload, account_sid=self._solution['account_sid'], )
def stream(self, customer_name=values.unset, friendly_name=values.unset,
iso_country=values.unset, limit=None, page_size=None):
"""
Streams AddressInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param unicode customer_name: The `customer_name` of the Address resources to read
:param unicode friendly_name: The string that identifies the Address resources to read
:param unicode iso_country: The ISO country code of the Address resources to read
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.api.v2010.account.address.AddressInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(
customer_name=customer_name,
friendly_name=friendly_name,
iso_country=iso_country,
page_size=limits['page_size'],
)
return self._version.stream(page, limits['limit'])
def list(self, customer_name=values.unset, friendly_name=values.unset,
iso_country=values.unset, limit=None, page_size=None):
"""
Lists AddressInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param unicode customer_name: The `customer_name` of the Address resources to read
:param unicode friendly_name: The string that identifies the Address resources to read
:param unicode iso_country: The ISO country code of the Address resources to read
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.api.v2010.account.address.AddressInstance]
"""
return list(self.stream(
customer_name=customer_name,
friendly_name=friendly_name,
iso_country=iso_country,
limit=limit,
page_size=page_size,
))
def page(self, customer_name=values.unset, friendly_name=values.unset,
iso_country=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
"""
Retrieve a single page of AddressInstance records from the API.
Request is executed immediately
:param unicode customer_name: The `customer_name` of the Address resources to read
:param unicode friendly_name: The string that identifies the Address resources to read
:param unicode iso_country: The ISO country code of the Address resources to read
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of AddressInstance
:rtype: twilio.rest.api.v2010.account.address.AddressPage
"""
data = values.of({
'CustomerName': customer_name,
'FriendlyName': friendly_name,
'IsoCountry': iso_country,
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(method='GET', uri=self._uri, params=data, )
return AddressPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of AddressInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of AddressInstance
:rtype: twilio.rest.api.v2010.account.address.AddressPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return AddressPage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a AddressContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.api.v2010.account.address.AddressContext
:rtype: twilio.rest.api.v2010.account.address.AddressContext
"""
return AddressContext(self._version, account_sid=self._solution['account_sid'], sid=sid, )
def __call__(self, sid):
"""
Constructs a AddressContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.api.v2010.account.address.AddressContext
:rtype: twilio.rest.api.v2010.account.address.AddressContext
"""
return AddressContext(self._version, account_sid=self._solution['account_sid'], sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Api.V2010.AddressList>'
class AddressPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the AddressPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param account_sid: The SID of the Account that is responsible for the resource
:returns: twilio.rest.api.v2010.account.address.AddressPage
:rtype: twilio.rest.api.v2010.account.address.AddressPage
"""
super(AddressPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of AddressInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.address.AddressInstance
:rtype: twilio.rest.api.v2010.account.address.AddressInstance
"""
return AddressInstance(self._version, payload, account_sid=self._solution['account_sid'], )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Api.V2010.AddressPage>'
class AddressContext(InstanceContext):
def __init__(self, version, account_sid, sid):
"""
Initialize the AddressContext
:param Version version: Version that contains the resource
:param account_sid: The SID of the Account that is responsible for this address
:param sid: The unique string that identifies the resource
:returns: twilio.rest.api.v2010.account.address.AddressContext
:rtype: twilio.rest.api.v2010.account.address.AddressContext
"""
super(AddressContext, self).__init__(version)
# Path Solution
self._solution = {'account_sid': account_sid, 'sid': sid, }
self._uri = '/Accounts/{account_sid}/Addresses/{sid}.json'.format(**self._solution)
# Dependents
self._dependent_phone_numbers = None
def delete(self):
"""
Deletes the AddressInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def fetch(self):
"""
Fetch the AddressInstance
:returns: The fetched AddressInstance
:rtype: twilio.rest.api.v2010.account.address.AddressInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return AddressInstance(
self._version,
payload,
account_sid=self._solution['account_sid'],
sid=self._solution['sid'],
)
def update(self, friendly_name=values.unset, customer_name=values.unset,
street=values.unset, city=values.unset, region=values.unset,
postal_code=values.unset, emergency_enabled=values.unset,
auto_correct_address=values.unset):
"""
Update the AddressInstance
:param unicode friendly_name: A string to describe the resource
:param unicode customer_name: The name to associate with the address
:param unicode street: The number and street address of the address
:param unicode city: The city of the address
:param unicode region: The state or region of the address
:param unicode postal_code: The postal code of the address
:param bool emergency_enabled: Whether to enable emergency calling on the address
:param bool auto_correct_address: Whether we should automatically correct the address
:returns: The updated AddressInstance
:rtype: twilio.rest.api.v2010.account.address.AddressInstance
"""
data = values.of({
'FriendlyName': friendly_name,
'CustomerName': customer_name,
'Street': street,
'City': city,
'Region': region,
'PostalCode': postal_code,
'EmergencyEnabled': emergency_enabled,
'AutoCorrectAddress': auto_correct_address,
})
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return AddressInstance(
self._version,
payload,
account_sid=self._solution['account_sid'],
sid=self._solution['sid'],
)
@property
def dependent_phone_numbers(self):
"""
Access the dependent_phone_numbers
:returns: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberList
:rtype: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberList
"""
if self._dependent_phone_numbers is None:
self._dependent_phone_numbers = DependentPhoneNumberList(
self._version,
account_sid=self._solution['account_sid'],
address_sid=self._solution['sid'],
)
return self._dependent_phone_numbers
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Api.V2010.AddressContext {}>'.format(context)
class AddressInstance(InstanceResource):
def __init__(self, version, payload, account_sid, sid=None):
"""
Initialize the AddressInstance
:returns: twilio.rest.api.v2010.account.address.AddressInstance
:rtype: twilio.rest.api.v2010.account.address.AddressInstance
"""
super(AddressInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'account_sid': payload.get('account_sid'),
'city': payload.get('city'),
'customer_name': payload.get('customer_name'),
'date_created': deserialize.rfc2822_datetime(payload.get('date_created')),
'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')),
'friendly_name': payload.get('friendly_name'),
'iso_country': payload.get('iso_country'),
'postal_code': payload.get('postal_code'),
'region': payload.get('region'),
'sid': payload.get('sid'),
'street': payload.get('street'),
'uri': payload.get('uri'),
'emergency_enabled': payload.get('emergency_enabled'),
'validated': payload.get('validated'),
'verified': payload.get('verified'),
}
# Context
self._context = None
self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: AddressContext for this AddressInstance
:rtype: twilio.rest.api.v2010.account.address.AddressContext
"""
if self._context is None:
self._context = AddressContext(
self._version,
account_sid=self._solution['account_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def account_sid(self):
"""
:returns: The SID of the Account that is responsible for the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def city(self):
"""
:returns: The city in which the address is located
:rtype: unicode
"""
return self._properties['city']
@property
def customer_name(self):
"""
:returns: The name associated with the address
:rtype: unicode
"""
return self._properties['customer_name']
@property
def date_created(self):
"""
:returns: The RFC 2822 date and time in GMT that the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The RFC 2822 date and time in GMT that the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def friendly_name(self):
"""
:returns: The string that you assigned to describe the resource
:rtype: unicode
"""
return self._properties['friendly_name']
@property
def iso_country(self):
"""
:returns: The ISO country code of the address
:rtype: unicode
"""
return self._properties['iso_country']
@property
def postal_code(self):
"""
:returns: The postal code of the address
:rtype: unicode
"""
return self._properties['postal_code']
@property
def region(self):
"""
:returns: The state or region of the address
:rtype: unicode
"""
return self._properties['region']
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def street(self):
"""
:returns: The number and street address of the address
:rtype: unicode
"""
return self._properties['street']
@property
def uri(self):
"""
:returns: The URI of the resource, relative to `https://api.twilio.com`
:rtype: unicode
"""
return self._properties['uri']
@property
def emergency_enabled(self):
"""
:returns: Whether emergency calling has been enabled on this number
:rtype: bool
"""
return self._properties['emergency_enabled']
@property
def validated(self):
"""
:returns: Whether the address has been validated to comply with local regulation
:rtype: bool
"""
return self._properties['validated']
@property
def verified(self):
"""
:returns: Whether the address has been verified to comply with regulation
:rtype: bool
"""
return self._properties['verified']
def delete(self):
"""
Deletes the AddressInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def fetch(self):
"""
Fetch the AddressInstance
:returns: The fetched AddressInstance
:rtype: twilio.rest.api.v2010.account.address.AddressInstance
"""
return self._proxy.fetch()
def update(self, friendly_name=values.unset, customer_name=values.unset,
street=values.unset, city=values.unset, region=values.unset,
postal_code=values.unset, emergency_enabled=values.unset,
auto_correct_address=values.unset):
"""
Update the AddressInstance
:param unicode friendly_name: A string to describe the resource
:param unicode customer_name: The name to associate with the address
:param unicode street: The number and street address of the address
:param unicode city: The city of the address
:param unicode region: The state or region of the address
:param unicode postal_code: The postal code of the address
:param bool emergency_enabled: Whether to enable emergency calling on the address
:param bool auto_correct_address: Whether we should automatically correct the address
:returns: The updated AddressInstance
:rtype: twilio.rest.api.v2010.account.address.AddressInstance
"""
return self._proxy.update(
friendly_name=friendly_name,
customer_name=customer_name,
street=street,
city=city,
region=region,
postal_code=postal_code,
emergency_enabled=emergency_enabled,
auto_correct_address=auto_correct_address,
)
@property
def dependent_phone_numbers(self):
"""
Access the dependent_phone_numbers
:returns: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberList
:rtype: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberList
"""
return self._proxy.dependent_phone_numbers
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Api.V2010.AddressInstance {}>'.format(context)
| mit | 8ddce5610b4d34a9c74293044160273e | 35.587646 | 103 | 0.619593 | 4.457189 | false | false | false | false |
twilio/twilio-python | twilio/rest/bulkexports/v1/export/__init__.py | 1 | 8712 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
from twilio.rest.bulkexports.v1.export.day import DayList
from twilio.rest.bulkexports.v1.export.export_custom_job import ExportCustomJobList
from twilio.rest.bulkexports.v1.export.job import JobList
class ExportList(ListResource):
def __init__(self, version):
"""
Initialize the ExportList
:param Version version: Version that contains the resource
:returns: twilio.rest.bulkexports.v1.export.ExportList
:rtype: twilio.rest.bulkexports.v1.export.ExportList
"""
super(ExportList, self).__init__(version)
# Path Solution
self._solution = {}
# Components
self._jobs = None
@property
def jobs(self):
"""
Access the jobs
:returns: twilio.rest.bulkexports.v1.export.job.JobList
:rtype: twilio.rest.bulkexports.v1.export.job.JobList
"""
if self._jobs is None:
self._jobs = JobList(self._version, )
return self._jobs
def get(self, resource_type):
"""
Constructs a ExportContext
:param resource_type: The type of communication – Messages, Calls, Conferences, and Participants
:returns: twilio.rest.bulkexports.v1.export.ExportContext
:rtype: twilio.rest.bulkexports.v1.export.ExportContext
"""
return ExportContext(self._version, resource_type=resource_type, )
def __call__(self, resource_type):
"""
Constructs a ExportContext
:param resource_type: The type of communication – Messages, Calls, Conferences, and Participants
:returns: twilio.rest.bulkexports.v1.export.ExportContext
:rtype: twilio.rest.bulkexports.v1.export.ExportContext
"""
return ExportContext(self._version, resource_type=resource_type, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Bulkexports.V1.ExportList>'
class ExportPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the ExportPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.bulkexports.v1.export.ExportPage
:rtype: twilio.rest.bulkexports.v1.export.ExportPage
"""
super(ExportPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of ExportInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.bulkexports.v1.export.ExportInstance
:rtype: twilio.rest.bulkexports.v1.export.ExportInstance
"""
return ExportInstance(self._version, payload, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Bulkexports.V1.ExportPage>'
class ExportContext(InstanceContext):
def __init__(self, version, resource_type):
"""
Initialize the ExportContext
:param Version version: Version that contains the resource
:param resource_type: The type of communication – Messages, Calls, Conferences, and Participants
:returns: twilio.rest.bulkexports.v1.export.ExportContext
:rtype: twilio.rest.bulkexports.v1.export.ExportContext
"""
super(ExportContext, self).__init__(version)
# Path Solution
self._solution = {'resource_type': resource_type, }
self._uri = '/Exports/{resource_type}'.format(**self._solution)
# Dependents
self._days = None
self._export_custom_jobs = None
def fetch(self):
"""
Fetch the ExportInstance
:returns: The fetched ExportInstance
:rtype: twilio.rest.bulkexports.v1.export.ExportInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return ExportInstance(self._version, payload, resource_type=self._solution['resource_type'], )
@property
def days(self):
"""
Access the days
:returns: twilio.rest.bulkexports.v1.export.day.DayList
:rtype: twilio.rest.bulkexports.v1.export.day.DayList
"""
if self._days is None:
self._days = DayList(self._version, resource_type=self._solution['resource_type'], )
return self._days
@property
def export_custom_jobs(self):
"""
Access the export_custom_jobs
:returns: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobList
:rtype: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobList
"""
if self._export_custom_jobs is None:
self._export_custom_jobs = ExportCustomJobList(
self._version,
resource_type=self._solution['resource_type'],
)
return self._export_custom_jobs
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Bulkexports.V1.ExportContext {}>'.format(context)
class ExportInstance(InstanceResource):
def __init__(self, version, payload, resource_type=None):
"""
Initialize the ExportInstance
:returns: twilio.rest.bulkexports.v1.export.ExportInstance
:rtype: twilio.rest.bulkexports.v1.export.ExportInstance
"""
super(ExportInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'resource_type': payload.get('resource_type'),
'url': payload.get('url'),
'links': payload.get('links'),
}
# Context
self._context = None
self._solution = {'resource_type': resource_type or self._properties['resource_type'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ExportContext for this ExportInstance
:rtype: twilio.rest.bulkexports.v1.export.ExportContext
"""
if self._context is None:
self._context = ExportContext(self._version, resource_type=self._solution['resource_type'], )
return self._context
@property
def resource_type(self):
"""
:returns: The type of communication – Messages, Calls, Conferences, and Participants
:rtype: unicode
"""
return self._properties['resource_type']
@property
def url(self):
"""
:returns: The URL of this resource.
:rtype: unicode
"""
return self._properties['url']
@property
def links(self):
"""
:returns: Nested resource URLs.
:rtype: unicode
"""
return self._properties['links']
def fetch(self):
"""
Fetch the ExportInstance
:returns: The fetched ExportInstance
:rtype: twilio.rest.bulkexports.v1.export.ExportInstance
"""
return self._proxy.fetch()
@property
def days(self):
"""
Access the days
:returns: twilio.rest.bulkexports.v1.export.day.DayList
:rtype: twilio.rest.bulkexports.v1.export.day.DayList
"""
return self._proxy.days
@property
def export_custom_jobs(self):
"""
Access the export_custom_jobs
:returns: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobList
:rtype: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobList
"""
return self._proxy.export_custom_jobs
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Bulkexports.V1.ExportInstance {}>'.format(context)
| mit | b2167191bd000145a6b655b7e8e09057 | 29.327526 | 105 | 0.62006 | 4.027765 | false | false | false | false |
twilio/twilio-python | twilio/rest/api/v2010/__init__.py | 2 | 5923 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base.version import Version
from twilio.rest.api.v2010.account import AccountContext
from twilio.rest.api.v2010.account import AccountList
class V2010(Version):
def __init__(self, domain):
"""
Initialize the V2010 version of Api
:returns: V2010 version of Api
:rtype: twilio.rest.api.v2010.V2010.V2010
"""
super(V2010, self).__init__(domain)
self.version = '2010-04-01'
self._accounts = None
self._account = None
@property
def accounts(self):
"""
:rtype: twilio.rest.api.v2010.account.AccountList
"""
if self._accounts is None:
self._accounts = AccountList(self)
return self._accounts
@property
def account(self):
"""
:returns: Account provided as the authenticating account
:rtype: AccountContext
"""
if self._account is None:
self._account = AccountContext(self, self.domain.twilio.account_sid)
return self._account
@account.setter
def account(self, value):
"""
Setter to override the primary account
:param AccountContext|AccountInstance value: account to use as primary account
"""
self._account = value
@property
def addresses(self):
"""
:rtype: twilio.rest.api.v2010.account.address.AddressList
"""
return self.account.addresses
@property
def applications(self):
"""
:rtype: twilio.rest.api.v2010.account.application.ApplicationList
"""
return self.account.applications
@property
def authorized_connect_apps(self):
"""
:rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList
"""
return self.account.authorized_connect_apps
@property
def available_phone_numbers(self):
"""
:rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList
"""
return self.account.available_phone_numbers
@property
def balance(self):
"""
:rtype: twilio.rest.api.v2010.account.balance.BalanceList
"""
return self.account.balance
@property
def calls(self):
"""
:rtype: twilio.rest.api.v2010.account.call.CallList
"""
return self.account.calls
@property
def conferences(self):
"""
:rtype: twilio.rest.api.v2010.account.conference.ConferenceList
"""
return self.account.conferences
@property
def connect_apps(self):
"""
:rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppList
"""
return self.account.connect_apps
@property
def incoming_phone_numbers(self):
"""
:rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberList
"""
return self.account.incoming_phone_numbers
@property
def keys(self):
"""
:rtype: twilio.rest.api.v2010.account.key.KeyList
"""
return self.account.keys
@property
def messages(self):
"""
:rtype: twilio.rest.api.v2010.account.message.MessageList
"""
return self.account.messages
@property
def new_keys(self):
"""
:rtype: twilio.rest.api.v2010.account.new_key.NewKeyList
"""
return self.account.new_keys
@property
def new_signing_keys(self):
"""
:rtype: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyList
"""
return self.account.new_signing_keys
@property
def notifications(self):
"""
:rtype: twilio.rest.api.v2010.account.notification.NotificationList
"""
return self.account.notifications
@property
def outgoing_caller_ids(self):
"""
:rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList
"""
return self.account.outgoing_caller_ids
@property
def queues(self):
"""
:rtype: twilio.rest.api.v2010.account.queue.QueueList
"""
return self.account.queues
@property
def recordings(self):
"""
:rtype: twilio.rest.api.v2010.account.recording.RecordingList
"""
return self.account.recordings
@property
def signing_keys(self):
"""
:rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyList
"""
return self.account.signing_keys
@property
def sip(self):
"""
:rtype: twilio.rest.api.v2010.account.sip.SipList
"""
return self.account.sip
@property
def short_codes(self):
"""
:rtype: twilio.rest.api.v2010.account.short_code.ShortCodeList
"""
return self.account.short_codes
@property
def tokens(self):
"""
:rtype: twilio.rest.api.v2010.account.token.TokenList
"""
return self.account.tokens
@property
def transcriptions(self):
"""
:rtype: twilio.rest.api.v2010.account.transcription.TranscriptionList
"""
return self.account.transcriptions
@property
def usage(self):
"""
:rtype: twilio.rest.api.v2010.account.usage.UsageList
"""
return self.account.usage
@property
def validation_requests(self):
"""
:rtype: twilio.rest.api.v2010.account.validation_request.ValidationRequestList
"""
return self.account.validation_requests
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Api.V2010>'
| mit | 8cd85aba46b6fec9075c8a1b80e9db3d | 24.640693 | 100 | 0.594631 | 4.010156 | false | false | false | false |
twilio/twilio-python | twilio/rest/proxy/v1/service/short_code.py | 1 | 15301 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class ShortCodeList(ListResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, service_sid):
"""
Initialize the ShortCodeList
:param Version version: Version that contains the resource
:param service_sid: The SID of the resource's parent Service
:returns: twilio.rest.proxy.v1.service.short_code.ShortCodeList
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeList
"""
super(ShortCodeList, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, }
self._uri = '/Services/{service_sid}/ShortCodes'.format(**self._solution)
def create(self, sid):
"""
Create the ShortCodeInstance
:param unicode sid: The SID of a Twilio ShortCode resource
:returns: The created ShortCodeInstance
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance
"""
data = values.of({'Sid': sid, })
payload = self._version.create(method='POST', uri=self._uri, data=data, )
return ShortCodeInstance(self._version, payload, service_sid=self._solution['service_sid'], )
def stream(self, limit=None, page_size=None):
"""
Streams ShortCodeInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.proxy.v1.service.short_code.ShortCodeInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
def list(self, limit=None, page_size=None):
"""
Lists ShortCodeInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.proxy.v1.service.short_code.ShortCodeInstance]
"""
return list(self.stream(limit=limit, page_size=page_size, ))
def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of ShortCodeInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of ShortCodeInstance
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodePage
"""
data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })
response = self._version.page(method='GET', uri=self._uri, params=data, )
return ShortCodePage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of ShortCodeInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of ShortCodeInstance
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodePage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return ShortCodePage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a ShortCodeContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.proxy.v1.service.short_code.ShortCodeContext
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeContext
"""
return ShortCodeContext(self._version, service_sid=self._solution['service_sid'], sid=sid, )
def __call__(self, sid):
"""
Constructs a ShortCodeContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.proxy.v1.service.short_code.ShortCodeContext
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeContext
"""
return ShortCodeContext(self._version, service_sid=self._solution['service_sid'], sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Proxy.V1.ShortCodeList>'
class ShortCodePage(Page):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, response, solution):
"""
Initialize the ShortCodePage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param service_sid: The SID of the resource's parent Service
:returns: twilio.rest.proxy.v1.service.short_code.ShortCodePage
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodePage
"""
super(ShortCodePage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of ShortCodeInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance
"""
return ShortCodeInstance(self._version, payload, service_sid=self._solution['service_sid'], )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Proxy.V1.ShortCodePage>'
class ShortCodeContext(InstanceContext):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, service_sid, sid):
"""
Initialize the ShortCodeContext
:param Version version: Version that contains the resource
:param service_sid: The SID of the parent Service to fetch the resource from
:param sid: The unique string that identifies the resource
:returns: twilio.rest.proxy.v1.service.short_code.ShortCodeContext
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeContext
"""
super(ShortCodeContext, self).__init__(version)
# Path Solution
self._solution = {'service_sid': service_sid, 'sid': sid, }
self._uri = '/Services/{service_sid}/ShortCodes/{sid}'.format(**self._solution)
def delete(self):
"""
Deletes the ShortCodeInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete(method='DELETE', uri=self._uri, )
def fetch(self):
"""
Fetch the ShortCodeInstance
:returns: The fetched ShortCodeInstance
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return ShortCodeInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
sid=self._solution['sid'],
)
def update(self, is_reserved=values.unset):
"""
Update the ShortCodeInstance
:param bool is_reserved: Whether the short code should be reserved for manual assignment to participants only
:returns: The updated ShortCodeInstance
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance
"""
data = values.of({'IsReserved': is_reserved, })
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return ShortCodeInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
sid=self._solution['sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Proxy.V1.ShortCodeContext {}>'.format(context)
class ShortCodeInstance(InstanceResource):
""" PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. """
def __init__(self, version, payload, service_sid, sid=None):
"""
Initialize the ShortCodeInstance
:returns: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance
"""
super(ShortCodeInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'account_sid': payload.get('account_sid'),
'service_sid': payload.get('service_sid'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'short_code': payload.get('short_code'),
'iso_country': payload.get('iso_country'),
'capabilities': payload.get('capabilities'),
'url': payload.get('url'),
'is_reserved': payload.get('is_reserved'),
}
# Context
self._context = None
self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ShortCodeContext for this ShortCodeInstance
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeContext
"""
if self._context is None:
self._context = ShortCodeContext(
self._version,
service_sid=self._solution['service_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def service_sid(self):
"""
:returns: The SID of the resource's parent Service
:rtype: unicode
"""
return self._properties['service_sid']
@property
def date_created(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def short_code(self):
"""
:returns: The short code's number
:rtype: unicode
"""
return self._properties['short_code']
@property
def iso_country(self):
"""
:returns: The ISO Country Code
:rtype: unicode
"""
return self._properties['iso_country']
@property
def capabilities(self):
"""
:returns: The capabilities of the short code
:rtype: unicode
"""
return self._properties['capabilities']
@property
def url(self):
"""
:returns: The absolute URL of the ShortCode resource
:rtype: unicode
"""
return self._properties['url']
@property
def is_reserved(self):
"""
:returns: Whether the short code should be reserved for manual assignment to participants only
:rtype: bool
"""
return self._properties['is_reserved']
def delete(self):
"""
Deletes the ShortCodeInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def fetch(self):
"""
Fetch the ShortCodeInstance
:returns: The fetched ShortCodeInstance
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance
"""
return self._proxy.fetch()
def update(self, is_reserved=values.unset):
"""
Update the ShortCodeInstance
:param bool is_reserved: Whether the short code should be reserved for manual assignment to participants only
:returns: The updated ShortCodeInstance
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance
"""
return self._proxy.update(is_reserved=is_reserved, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Proxy.V1.ShortCodeInstance {}>'.format(context)
| mit | cb6738fd5aceadb54eefe2f83f8ef265 | 33.461712 | 117 | 0.617607 | 4.338248 | false | false | false | false |
twilio/twilio-python | tests/integration/conversations/v1/user/test_user_conversation.py | 1 | 10243 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class UserConversationTestCase(IntegrationTestCase):
def test_update_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.conversations.v1.users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.user_conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update()
self.holodeck.assert_has_request(Request(
'post',
'https://conversations.twilio.com/v1/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
))
def test_update_response(self):
self.holodeck.mock(Response(
200,
'''
{
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"chat_service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"unread_messages_count": 100,
"last_read_message_index": 100,
"participant_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"friendly_name": "friendly_name",
"conversation_state": "inactive",
"timers": {
"date_inactive": "2015-12-16T22:19:38Z",
"date_closed": "2015-12-16T22:28:38Z"
},
"attributes": "{}",
"date_created": "2015-07-30T20:00:00Z",
"date_updated": "2015-07-30T20:00:00Z",
"created_by": "created_by",
"notification_level": "default",
"unique_name": "unique_name",
"url": "https://conversations.twilio.com/v1/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"links": {
"participant": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"conversation": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
}
'''
))
actual = self.client.conversations.v1.users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.user_conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update()
self.assertIsNotNone(actual)
def test_delete_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.conversations.v1.users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.user_conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete()
self.holodeck.assert_has_request(Request(
'delete',
'https://conversations.twilio.com/v1/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
))
def test_delete_response(self):
self.holodeck.mock(Response(
204,
None,
))
actual = self.client.conversations.v1.users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.user_conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete()
self.assertTrue(actual)
def test_fetch_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.conversations.v1.users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.user_conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()
self.holodeck.assert_has_request(Request(
'get',
'https://conversations.twilio.com/v1/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
))
def test_fetch_response(self):
self.holodeck.mock(Response(
200,
'''
{
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"chat_service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"unread_messages_count": 100,
"last_read_message_index": 100,
"participant_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"friendly_name": "friendly_name",
"conversation_state": "inactive",
"timers": {
"date_inactive": "2015-12-16T22:19:38Z",
"date_closed": "2015-12-16T22:28:38Z"
},
"attributes": "{}",
"date_created": "2015-07-30T20:00:00Z",
"date_updated": "2015-07-30T20:00:00Z",
"created_by": "created_by",
"notification_level": "default",
"unique_name": "unique_name",
"url": "https://conversations.twilio.com/v1/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"links": {
"participant": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"conversation": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
}
'''
))
actual = self.client.conversations.v1.users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.user_conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()
self.assertIsNotNone(actual)
def test_list_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.conversations.v1.users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.user_conversations.list()
self.holodeck.assert_has_request(Request(
'get',
'https://conversations.twilio.com/v1/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conversations',
))
def test_read_empty_response(self):
self.holodeck.mock(Response(
200,
'''
{
"conversations": [],
"meta": {
"page": 0,
"page_size": 50,
"first_page_url": "https://conversations.twilio.com/v1/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conversations?PageSize=50&Page=0",
"previous_page_url": null,
"url": "https://conversations.twilio.com/v1/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conversations?PageSize=50&Page=0",
"next_page_url": null,
"key": "conversations"
}
}
'''
))
actual = self.client.conversations.v1.users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.user_conversations.list()
self.assertIsNotNone(actual)
def test_read_full_response(self):
self.holodeck.mock(Response(
200,
'''
{
"conversations": [
{
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"chat_service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"unread_messages_count": 100,
"last_read_message_index": 100,
"participant_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"friendly_name": "friendly_name",
"conversation_state": "inactive",
"timers": {
"date_inactive": "2015-12-16T22:19:38Z",
"date_closed": "2015-12-16T22:28:38Z"
},
"attributes": "{}",
"date_created": "2015-07-30T20:00:00Z",
"date_updated": "2015-07-30T20:00:00Z",
"created_by": "created_by",
"notification_level": "default",
"unique_name": "unique_name",
"url": "https://conversations.twilio.com/v1/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"links": {
"participant": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"conversation": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
}
],
"meta": {
"page": 0,
"page_size": 50,
"first_page_url": "https://conversations.twilio.com/v1/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conversations?PageSize=50&Page=0",
"previous_page_url": null,
"url": "https://conversations.twilio.com/v1/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conversations?PageSize=50&Page=0",
"next_page_url": null,
"key": "conversations"
}
}
'''
))
actual = self.client.conversations.v1.users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.user_conversations.list()
self.assertIsNotNone(actual)
| mit | 06559c0980ab237bcde2bc84b869823d | 44.524444 | 178 | 0.555501 | 4.65168 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.