prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
<|fim_middle|>
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | """Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state() |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
<|fim_middle|>
<|fim▁end|> | """State is assumed, if no template given."""
return self._template is None |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
<|fim_middle|>
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | self._state = None
return |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
<|fim_middle|>
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
<|fim_middle|>
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | self._state = state.state == STATE_ON |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
<|fim_middle|>
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | self.add_template_attribute(
"_state", self._template, None, self._update_state
) |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
<|fim_middle|>
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | self._state = True
self.async_write_ha_state() |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
<|fim_middle|>
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | self._state = False
self.async_write_ha_state() |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def <|fim_middle|>(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | _async_create_entities |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def <|fim_middle|>(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | async_setup_platform |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def <|fim_middle|>(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | __init__ |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def <|fim_middle|>(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | _update_state |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def <|fim_middle|>(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | async_added_to_hass |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def <|fim_middle|>(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | name |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def <|fim_middle|>(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | unique_id |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def <|fim_middle|>(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | is_on |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def <|fim_middle|>(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | should_poll |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def <|fim_middle|>(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | async_turn_on |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def <|fim_middle|>(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | async_turn_off |
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def <|fim_middle|>(self):
"""State is assumed, if no template given."""
return self._template is None
<|fim▁end|> | assumed_state |
<|file_name|>resolve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
from src.sqllist import GLOBALS
class BasicResolver(object):
"""General resolver class"""
def __init__(self, conn=None):
self.conn = conn
pass
def resolve(self, detections, sources):
"""Template resolve function.
Returns resolution status and an array of xtrsrcid-runcatid of
resolved pairs (if possible)."""
return False, []
def load_detections(self, group_id):
cursor = self.conn.get_cursor("""
select xtrsrcid, ra, ra_err, decl, decl_err, f_int, f_int_err
from extractedsources e
where e.image_id = %s
and exists (select 1 from temp_associations ta
where ta.xtrsrc_id2 = e.xtrsrcid
and ta.image_id = e.image_id
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
detections = cursor.fetchall()
cursor.close()
return detections
def load_sources(self, group_id):<|fim▁hole|> images i
where i.imageid = %s
and f.band = i.band
and f.stokes = i.stokes
and r.runcatid = f.runcat_id
and exists (select 1 from temp_associations ta
where ta.runcat_id = r.runcatid
and ta.image_id = i.imageid
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
sources = cursor.fetchall()
cursor.close()
return sources
def run_resolve(self, group_id):
"""Get data from Database,
run resolver,
saev results to temp_associations"""
#--Run resolver--
is_ok, solutions = self.resolve(self.load_detections(group_id),
self.load_sources(group_id))
if is_ok:
#"delete" all associations from this group.
self.conn.execute("""
update temp_associations
set kind = -1
where image_id = %s
and group_head_id = %s;""" % (GLOBALS['i'], group_id))
#"restore" associations that are "ok"
for solution in solutions:
self.conn.execute("""update temp_associations
set kind = 1,
group_head_id = null
where image_id = %s
and group_head_id = %s
and xtrsrc_id2 = %s
and runcat_id = %s;""" % (GLOBALS['i'], group_id,
solution[0], solution[1]))
return is_ok<|fim▁end|> | cursor = self.conn.get_cursor("""
select runcatid, wm_ra, wm_ra_err, wm_decl, wm_decl_err, wm_f_int, wm_f_int_err
from runningcatalog r,
runningcatalog_fluxes f, |
<|file_name|>resolve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
from src.sqllist import GLOBALS
class BasicResolver(object):
<|fim_middle|>
<|fim▁end|> | """General resolver class"""
def __init__(self, conn=None):
self.conn = conn
pass
def resolve(self, detections, sources):
"""Template resolve function.
Returns resolution status and an array of xtrsrcid-runcatid of
resolved pairs (if possible)."""
return False, []
def load_detections(self, group_id):
cursor = self.conn.get_cursor("""
select xtrsrcid, ra, ra_err, decl, decl_err, f_int, f_int_err
from extractedsources e
where e.image_id = %s
and exists (select 1 from temp_associations ta
where ta.xtrsrc_id2 = e.xtrsrcid
and ta.image_id = e.image_id
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
detections = cursor.fetchall()
cursor.close()
return detections
def load_sources(self, group_id):
cursor = self.conn.get_cursor("""
select runcatid, wm_ra, wm_ra_err, wm_decl, wm_decl_err, wm_f_int, wm_f_int_err
from runningcatalog r,
runningcatalog_fluxes f,
images i
where i.imageid = %s
and f.band = i.band
and f.stokes = i.stokes
and r.runcatid = f.runcat_id
and exists (select 1 from temp_associations ta
where ta.runcat_id = r.runcatid
and ta.image_id = i.imageid
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
sources = cursor.fetchall()
cursor.close()
return sources
def run_resolve(self, group_id):
"""Get data from Database,
run resolver,
saev results to temp_associations"""
#--Run resolver--
is_ok, solutions = self.resolve(self.load_detections(group_id),
self.load_sources(group_id))
if is_ok:
#"delete" all associations from this group.
self.conn.execute("""
update temp_associations
set kind = -1
where image_id = %s
and group_head_id = %s;""" % (GLOBALS['i'], group_id))
#"restore" associations that are "ok"
for solution in solutions:
self.conn.execute("""update temp_associations
set kind = 1,
group_head_id = null
where image_id = %s
and group_head_id = %s
and xtrsrc_id2 = %s
and runcat_id = %s;""" % (GLOBALS['i'], group_id,
solution[0], solution[1]))
return is_ok |
<|file_name|>resolve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
from src.sqllist import GLOBALS
class BasicResolver(object):
"""General resolver class"""
def __init__(self, conn=None):
<|fim_middle|>
def resolve(self, detections, sources):
"""Template resolve function.
Returns resolution status and an array of xtrsrcid-runcatid of
resolved pairs (if possible)."""
return False, []
def load_detections(self, group_id):
cursor = self.conn.get_cursor("""
select xtrsrcid, ra, ra_err, decl, decl_err, f_int, f_int_err
from extractedsources e
where e.image_id = %s
and exists (select 1 from temp_associations ta
where ta.xtrsrc_id2 = e.xtrsrcid
and ta.image_id = e.image_id
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
detections = cursor.fetchall()
cursor.close()
return detections
def load_sources(self, group_id):
cursor = self.conn.get_cursor("""
select runcatid, wm_ra, wm_ra_err, wm_decl, wm_decl_err, wm_f_int, wm_f_int_err
from runningcatalog r,
runningcatalog_fluxes f,
images i
where i.imageid = %s
and f.band = i.band
and f.stokes = i.stokes
and r.runcatid = f.runcat_id
and exists (select 1 from temp_associations ta
where ta.runcat_id = r.runcatid
and ta.image_id = i.imageid
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
sources = cursor.fetchall()
cursor.close()
return sources
def run_resolve(self, group_id):
"""Get data from Database,
run resolver,
saev results to temp_associations"""
#--Run resolver--
is_ok, solutions = self.resolve(self.load_detections(group_id),
self.load_sources(group_id))
if is_ok:
#"delete" all associations from this group.
self.conn.execute("""
update temp_associations
set kind = -1
where image_id = %s
and group_head_id = %s;""" % (GLOBALS['i'], group_id))
#"restore" associations that are "ok"
for solution in solutions:
self.conn.execute("""update temp_associations
set kind = 1,
group_head_id = null
where image_id = %s
and group_head_id = %s
and xtrsrc_id2 = %s
and runcat_id = %s;""" % (GLOBALS['i'], group_id,
solution[0], solution[1]))
return is_ok
<|fim▁end|> | self.conn = conn
pass |
<|file_name|>resolve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
from src.sqllist import GLOBALS
class BasicResolver(object):
"""General resolver class"""
def __init__(self, conn=None):
self.conn = conn
pass
def resolve(self, detections, sources):
<|fim_middle|>
def load_detections(self, group_id):
cursor = self.conn.get_cursor("""
select xtrsrcid, ra, ra_err, decl, decl_err, f_int, f_int_err
from extractedsources e
where e.image_id = %s
and exists (select 1 from temp_associations ta
where ta.xtrsrc_id2 = e.xtrsrcid
and ta.image_id = e.image_id
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
detections = cursor.fetchall()
cursor.close()
return detections
def load_sources(self, group_id):
cursor = self.conn.get_cursor("""
select runcatid, wm_ra, wm_ra_err, wm_decl, wm_decl_err, wm_f_int, wm_f_int_err
from runningcatalog r,
runningcatalog_fluxes f,
images i
where i.imageid = %s
and f.band = i.band
and f.stokes = i.stokes
and r.runcatid = f.runcat_id
and exists (select 1 from temp_associations ta
where ta.runcat_id = r.runcatid
and ta.image_id = i.imageid
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
sources = cursor.fetchall()
cursor.close()
return sources
def run_resolve(self, group_id):
"""Get data from Database,
run resolver,
saev results to temp_associations"""
#--Run resolver--
is_ok, solutions = self.resolve(self.load_detections(group_id),
self.load_sources(group_id))
if is_ok:
#"delete" all associations from this group.
self.conn.execute("""
update temp_associations
set kind = -1
where image_id = %s
and group_head_id = %s;""" % (GLOBALS['i'], group_id))
#"restore" associations that are "ok"
for solution in solutions:
self.conn.execute("""update temp_associations
set kind = 1,
group_head_id = null
where image_id = %s
and group_head_id = %s
and xtrsrc_id2 = %s
and runcat_id = %s;""" % (GLOBALS['i'], group_id,
solution[0], solution[1]))
return is_ok
<|fim▁end|> | """Template resolve function.
Returns resolution status and an array of xtrsrcid-runcatid of
resolved pairs (if possible)."""
return False, [] |
<|file_name|>resolve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
from src.sqllist import GLOBALS
class BasicResolver(object):
"""General resolver class"""
def __init__(self, conn=None):
self.conn = conn
pass
def resolve(self, detections, sources):
"""Template resolve function.
Returns resolution status and an array of xtrsrcid-runcatid of
resolved pairs (if possible)."""
return False, []
def load_detections(self, group_id):
<|fim_middle|>
def load_sources(self, group_id):
cursor = self.conn.get_cursor("""
select runcatid, wm_ra, wm_ra_err, wm_decl, wm_decl_err, wm_f_int, wm_f_int_err
from runningcatalog r,
runningcatalog_fluxes f,
images i
where i.imageid = %s
and f.band = i.band
and f.stokes = i.stokes
and r.runcatid = f.runcat_id
and exists (select 1 from temp_associations ta
where ta.runcat_id = r.runcatid
and ta.image_id = i.imageid
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
sources = cursor.fetchall()
cursor.close()
return sources
def run_resolve(self, group_id):
"""Get data from Database,
run resolver,
saev results to temp_associations"""
#--Run resolver--
is_ok, solutions = self.resolve(self.load_detections(group_id),
self.load_sources(group_id))
if is_ok:
#"delete" all associations from this group.
self.conn.execute("""
update temp_associations
set kind = -1
where image_id = %s
and group_head_id = %s;""" % (GLOBALS['i'], group_id))
#"restore" associations that are "ok"
for solution in solutions:
self.conn.execute("""update temp_associations
set kind = 1,
group_head_id = null
where image_id = %s
and group_head_id = %s
and xtrsrc_id2 = %s
and runcat_id = %s;""" % (GLOBALS['i'], group_id,
solution[0], solution[1]))
return is_ok
<|fim▁end|> | cursor = self.conn.get_cursor("""
select xtrsrcid, ra, ra_err, decl, decl_err, f_int, f_int_err
from extractedsources e
where e.image_id = %s
and exists (select 1 from temp_associations ta
where ta.xtrsrc_id2 = e.xtrsrcid
and ta.image_id = e.image_id
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
detections = cursor.fetchall()
cursor.close()
return detections |
<|file_name|>resolve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
from src.sqllist import GLOBALS
class BasicResolver(object):
"""General resolver class"""
def __init__(self, conn=None):
self.conn = conn
pass
def resolve(self, detections, sources):
"""Template resolve function.
Returns resolution status and an array of xtrsrcid-runcatid of
resolved pairs (if possible)."""
return False, []
def load_detections(self, group_id):
cursor = self.conn.get_cursor("""
select xtrsrcid, ra, ra_err, decl, decl_err, f_int, f_int_err
from extractedsources e
where e.image_id = %s
and exists (select 1 from temp_associations ta
where ta.xtrsrc_id2 = e.xtrsrcid
and ta.image_id = e.image_id
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
detections = cursor.fetchall()
cursor.close()
return detections
def load_sources(self, group_id):
<|fim_middle|>
def run_resolve(self, group_id):
"""Get data from Database,
run resolver,
saev results to temp_associations"""
#--Run resolver--
is_ok, solutions = self.resolve(self.load_detections(group_id),
self.load_sources(group_id))
if is_ok:
#"delete" all associations from this group.
self.conn.execute("""
update temp_associations
set kind = -1
where image_id = %s
and group_head_id = %s;""" % (GLOBALS['i'], group_id))
#"restore" associations that are "ok"
for solution in solutions:
self.conn.execute("""update temp_associations
set kind = 1,
group_head_id = null
where image_id = %s
and group_head_id = %s
and xtrsrc_id2 = %s
and runcat_id = %s;""" % (GLOBALS['i'], group_id,
solution[0], solution[1]))
return is_ok
<|fim▁end|> | cursor = self.conn.get_cursor("""
select runcatid, wm_ra, wm_ra_err, wm_decl, wm_decl_err, wm_f_int, wm_f_int_err
from runningcatalog r,
runningcatalog_fluxes f,
images i
where i.imageid = %s
and f.band = i.band
and f.stokes = i.stokes
and r.runcatid = f.runcat_id
and exists (select 1 from temp_associations ta
where ta.runcat_id = r.runcatid
and ta.image_id = i.imageid
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
sources = cursor.fetchall()
cursor.close()
return sources |
<|file_name|>resolve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
from src.sqllist import GLOBALS
class BasicResolver(object):
"""General resolver class"""
def __init__(self, conn=None):
self.conn = conn
pass
def resolve(self, detections, sources):
"""Template resolve function.
Returns resolution status and an array of xtrsrcid-runcatid of
resolved pairs (if possible)."""
return False, []
def load_detections(self, group_id):
cursor = self.conn.get_cursor("""
select xtrsrcid, ra, ra_err, decl, decl_err, f_int, f_int_err
from extractedsources e
where e.image_id = %s
and exists (select 1 from temp_associations ta
where ta.xtrsrc_id2 = e.xtrsrcid
and ta.image_id = e.image_id
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
detections = cursor.fetchall()
cursor.close()
return detections
def load_sources(self, group_id):
cursor = self.conn.get_cursor("""
select runcatid, wm_ra, wm_ra_err, wm_decl, wm_decl_err, wm_f_int, wm_f_int_err
from runningcatalog r,
runningcatalog_fluxes f,
images i
where i.imageid = %s
and f.band = i.band
and f.stokes = i.stokes
and r.runcatid = f.runcat_id
and exists (select 1 from temp_associations ta
where ta.runcat_id = r.runcatid
and ta.image_id = i.imageid
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
sources = cursor.fetchall()
cursor.close()
return sources
def run_resolve(self, group_id):
<|fim_middle|>
<|fim▁end|> | """Get data from Database,
run resolver,
saev results to temp_associations"""
#--Run resolver--
is_ok, solutions = self.resolve(self.load_detections(group_id),
self.load_sources(group_id))
if is_ok:
#"delete" all associations from this group.
self.conn.execute("""
update temp_associations
set kind = -1
where image_id = %s
and group_head_id = %s;""" % (GLOBALS['i'], group_id))
#"restore" associations that are "ok"
for solution in solutions:
self.conn.execute("""update temp_associations
set kind = 1,
group_head_id = null
where image_id = %s
and group_head_id = %s
and xtrsrc_id2 = %s
and runcat_id = %s;""" % (GLOBALS['i'], group_id,
solution[0], solution[1]))
return is_ok |
<|file_name|>resolve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
from src.sqllist import GLOBALS
class BasicResolver(object):
"""General resolver class"""
def __init__(self, conn=None):
self.conn = conn
pass
def resolve(self, detections, sources):
"""Template resolve function.
Returns resolution status and an array of xtrsrcid-runcatid of
resolved pairs (if possible)."""
return False, []
def load_detections(self, group_id):
cursor = self.conn.get_cursor("""
select xtrsrcid, ra, ra_err, decl, decl_err, f_int, f_int_err
from extractedsources e
where e.image_id = %s
and exists (select 1 from temp_associations ta
where ta.xtrsrc_id2 = e.xtrsrcid
and ta.image_id = e.image_id
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
detections = cursor.fetchall()
cursor.close()
return detections
def load_sources(self, group_id):
cursor = self.conn.get_cursor("""
select runcatid, wm_ra, wm_ra_err, wm_decl, wm_decl_err, wm_f_int, wm_f_int_err
from runningcatalog r,
runningcatalog_fluxes f,
images i
where i.imageid = %s
and f.band = i.band
and f.stokes = i.stokes
and r.runcatid = f.runcat_id
and exists (select 1 from temp_associations ta
where ta.runcat_id = r.runcatid
and ta.image_id = i.imageid
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
sources = cursor.fetchall()
cursor.close()
return sources
def run_resolve(self, group_id):
"""Get data from Database,
run resolver,
saev results to temp_associations"""
#--Run resolver--
is_ok, solutions = self.resolve(self.load_detections(group_id),
self.load_sources(group_id))
if is_ok:
#"delete" all associations from this group.
<|fim_middle|>
return is_ok
<|fim▁end|> | self.conn.execute("""
update temp_associations
set kind = -1
where image_id = %s
and group_head_id = %s;""" % (GLOBALS['i'], group_id))
#"restore" associations that are "ok"
for solution in solutions:
self.conn.execute("""update temp_associations
set kind = 1,
group_head_id = null
where image_id = %s
and group_head_id = %s
and xtrsrc_id2 = %s
and runcat_id = %s;""" % (GLOBALS['i'], group_id,
solution[0], solution[1])) |
<|file_name|>resolve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
from src.sqllist import GLOBALS
class BasicResolver(object):
"""General resolver class"""
def <|fim_middle|>(self, conn=None):
self.conn = conn
pass
def resolve(self, detections, sources):
"""Template resolve function.
Returns resolution status and an array of xtrsrcid-runcatid of
resolved pairs (if possible)."""
return False, []
def load_detections(self, group_id):
cursor = self.conn.get_cursor("""
select xtrsrcid, ra, ra_err, decl, decl_err, f_int, f_int_err
from extractedsources e
where e.image_id = %s
and exists (select 1 from temp_associations ta
where ta.xtrsrc_id2 = e.xtrsrcid
and ta.image_id = e.image_id
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
detections = cursor.fetchall()
cursor.close()
return detections
def load_sources(self, group_id):
cursor = self.conn.get_cursor("""
select runcatid, wm_ra, wm_ra_err, wm_decl, wm_decl_err, wm_f_int, wm_f_int_err
from runningcatalog r,
runningcatalog_fluxes f,
images i
where i.imageid = %s
and f.band = i.band
and f.stokes = i.stokes
and r.runcatid = f.runcat_id
and exists (select 1 from temp_associations ta
where ta.runcat_id = r.runcatid
and ta.image_id = i.imageid
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
sources = cursor.fetchall()
cursor.close()
return sources
def run_resolve(self, group_id):
"""Get data from Database,
run resolver,
saev results to temp_associations"""
#--Run resolver--
is_ok, solutions = self.resolve(self.load_detections(group_id),
self.load_sources(group_id))
if is_ok:
#"delete" all associations from this group.
self.conn.execute("""
update temp_associations
set kind = -1
where image_id = %s
and group_head_id = %s;""" % (GLOBALS['i'], group_id))
#"restore" associations that are "ok"
for solution in solutions:
self.conn.execute("""update temp_associations
set kind = 1,
group_head_id = null
where image_id = %s
and group_head_id = %s
and xtrsrc_id2 = %s
and runcat_id = %s;""" % (GLOBALS['i'], group_id,
solution[0], solution[1]))
return is_ok
<|fim▁end|> | __init__ |
<|file_name|>resolve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
from src.sqllist import GLOBALS
class BasicResolver(object):
"""General resolver class"""
def __init__(self, conn=None):
self.conn = conn
pass
def <|fim_middle|>(self, detections, sources):
"""Template resolve function.
Returns resolution status and an array of xtrsrcid-runcatid of
resolved pairs (if possible)."""
return False, []
def load_detections(self, group_id):
cursor = self.conn.get_cursor("""
select xtrsrcid, ra, ra_err, decl, decl_err, f_int, f_int_err
from extractedsources e
where e.image_id = %s
and exists (select 1 from temp_associations ta
where ta.xtrsrc_id2 = e.xtrsrcid
and ta.image_id = e.image_id
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
detections = cursor.fetchall()
cursor.close()
return detections
def load_sources(self, group_id):
cursor = self.conn.get_cursor("""
select runcatid, wm_ra, wm_ra_err, wm_decl, wm_decl_err, wm_f_int, wm_f_int_err
from runningcatalog r,
runningcatalog_fluxes f,
images i
where i.imageid = %s
and f.band = i.band
and f.stokes = i.stokes
and r.runcatid = f.runcat_id
and exists (select 1 from temp_associations ta
where ta.runcat_id = r.runcatid
and ta.image_id = i.imageid
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
sources = cursor.fetchall()
cursor.close()
return sources
def run_resolve(self, group_id):
"""Get data from Database,
run resolver,
saev results to temp_associations"""
#--Run resolver--
is_ok, solutions = self.resolve(self.load_detections(group_id),
self.load_sources(group_id))
if is_ok:
#"delete" all associations from this group.
self.conn.execute("""
update temp_associations
set kind = -1
where image_id = %s
and group_head_id = %s;""" % (GLOBALS['i'], group_id))
#"restore" associations that are "ok"
for solution in solutions:
self.conn.execute("""update temp_associations
set kind = 1,
group_head_id = null
where image_id = %s
and group_head_id = %s
and xtrsrc_id2 = %s
and runcat_id = %s;""" % (GLOBALS['i'], group_id,
solution[0], solution[1]))
return is_ok
<|fim▁end|> | resolve |
<|file_name|>resolve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
from src.sqllist import GLOBALS
class BasicResolver(object):
"""General resolver class"""
def __init__(self, conn=None):
self.conn = conn
pass
def resolve(self, detections, sources):
"""Template resolve function.
Returns resolution status and an array of xtrsrcid-runcatid of
resolved pairs (if possible)."""
return False, []
def <|fim_middle|>(self, group_id):
cursor = self.conn.get_cursor("""
select xtrsrcid, ra, ra_err, decl, decl_err, f_int, f_int_err
from extractedsources e
where e.image_id = %s
and exists (select 1 from temp_associations ta
where ta.xtrsrc_id2 = e.xtrsrcid
and ta.image_id = e.image_id
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
detections = cursor.fetchall()
cursor.close()
return detections
def load_sources(self, group_id):
cursor = self.conn.get_cursor("""
select runcatid, wm_ra, wm_ra_err, wm_decl, wm_decl_err, wm_f_int, wm_f_int_err
from runningcatalog r,
runningcatalog_fluxes f,
images i
where i.imageid = %s
and f.band = i.band
and f.stokes = i.stokes
and r.runcatid = f.runcat_id
and exists (select 1 from temp_associations ta
where ta.runcat_id = r.runcatid
and ta.image_id = i.imageid
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
sources = cursor.fetchall()
cursor.close()
return sources
def run_resolve(self, group_id):
"""Get data from Database,
run resolver,
saev results to temp_associations"""
#--Run resolver--
is_ok, solutions = self.resolve(self.load_detections(group_id),
self.load_sources(group_id))
if is_ok:
#"delete" all associations from this group.
self.conn.execute("""
update temp_associations
set kind = -1
where image_id = %s
and group_head_id = %s;""" % (GLOBALS['i'], group_id))
#"restore" associations that are "ok"
for solution in solutions:
self.conn.execute("""update temp_associations
set kind = 1,
group_head_id = null
where image_id = %s
and group_head_id = %s
and xtrsrc_id2 = %s
and runcat_id = %s;""" % (GLOBALS['i'], group_id,
solution[0], solution[1]))
return is_ok
<|fim▁end|> | load_detections |
<|file_name|>resolve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
from src.sqllist import GLOBALS
class BasicResolver(object):
"""General resolver class"""
def __init__(self, conn=None):
self.conn = conn
pass
def resolve(self, detections, sources):
"""Template resolve function.
Returns resolution status and an array of xtrsrcid-runcatid of
resolved pairs (if possible)."""
return False, []
def load_detections(self, group_id):
cursor = self.conn.get_cursor("""
select xtrsrcid, ra, ra_err, decl, decl_err, f_int, f_int_err
from extractedsources e
where e.image_id = %s
and exists (select 1 from temp_associations ta
where ta.xtrsrc_id2 = e.xtrsrcid
and ta.image_id = e.image_id
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
detections = cursor.fetchall()
cursor.close()
return detections
def <|fim_middle|>(self, group_id):
cursor = self.conn.get_cursor("""
select runcatid, wm_ra, wm_ra_err, wm_decl, wm_decl_err, wm_f_int, wm_f_int_err
from runningcatalog r,
runningcatalog_fluxes f,
images i
where i.imageid = %s
and f.band = i.band
and f.stokes = i.stokes
and r.runcatid = f.runcat_id
and exists (select 1 from temp_associations ta
where ta.runcat_id = r.runcatid
and ta.image_id = i.imageid
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
sources = cursor.fetchall()
cursor.close()
return sources
def run_resolve(self, group_id):
"""Get data from Database,
run resolver,
saev results to temp_associations"""
#--Run resolver--
is_ok, solutions = self.resolve(self.load_detections(group_id),
self.load_sources(group_id))
if is_ok:
#"delete" all associations from this group.
self.conn.execute("""
update temp_associations
set kind = -1
where image_id = %s
and group_head_id = %s;""" % (GLOBALS['i'], group_id))
#"restore" associations that are "ok"
for solution in solutions:
self.conn.execute("""update temp_associations
set kind = 1,
group_head_id = null
where image_id = %s
and group_head_id = %s
and xtrsrc_id2 = %s
and runcat_id = %s;""" % (GLOBALS['i'], group_id,
solution[0], solution[1]))
return is_ok
<|fim▁end|> | load_sources |
<|file_name|>resolve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
from src.sqllist import GLOBALS
class BasicResolver(object):
"""General resolver class"""
def __init__(self, conn=None):
self.conn = conn
pass
def resolve(self, detections, sources):
"""Template resolve function.
Returns resolution status and an array of xtrsrcid-runcatid of
resolved pairs (if possible)."""
return False, []
def load_detections(self, group_id):
cursor = self.conn.get_cursor("""
select xtrsrcid, ra, ra_err, decl, decl_err, f_int, f_int_err
from extractedsources e
where e.image_id = %s
and exists (select 1 from temp_associations ta
where ta.xtrsrc_id2 = e.xtrsrcid
and ta.image_id = e.image_id
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
detections = cursor.fetchall()
cursor.close()
return detections
def load_sources(self, group_id):
cursor = self.conn.get_cursor("""
select runcatid, wm_ra, wm_ra_err, wm_decl, wm_decl_err, wm_f_int, wm_f_int_err
from runningcatalog r,
runningcatalog_fluxes f,
images i
where i.imageid = %s
and f.band = i.band
and f.stokes = i.stokes
and r.runcatid = f.runcat_id
and exists (select 1 from temp_associations ta
where ta.runcat_id = r.runcatid
and ta.image_id = i.imageid
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
sources = cursor.fetchall()
cursor.close()
return sources
def <|fim_middle|>(self, group_id):
"""Get data from Database,
run resolver,
saev results to temp_associations"""
#--Run resolver--
is_ok, solutions = self.resolve(self.load_detections(group_id),
self.load_sources(group_id))
if is_ok:
#"delete" all associations from this group.
self.conn.execute("""
update temp_associations
set kind = -1
where image_id = %s
and group_head_id = %s;""" % (GLOBALS['i'], group_id))
#"restore" associations that are "ok"
for solution in solutions:
self.conn.execute("""update temp_associations
set kind = 1,
group_head_id = null
where image_id = %s
and group_head_id = %s
and xtrsrc_id2 = %s
and runcat_id = %s;""" % (GLOBALS['i'], group_id,
solution[0], solution[1]))
return is_ok
<|fim▁end|> | run_resolve |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__<|fim▁hole|> if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)<|fim▁end|> |
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items(): |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
<|fim_middle|>
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | """Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
<|fim_middle|>
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params) |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
<|fim_middle|>
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | self.email = email
self.params = params |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
<|fim_middle|>
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params) |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
<|fim_middle|>
<|fim▁end|> | """For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params) |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
<|fim_middle|>
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | return '' |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
<|fim_middle|>
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | params = params.__dict__ |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
<|fim_middle|>
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
<|fim_middle|>
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | actual_params[k] = value |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
<|fim_middle|>
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | if value < 1 or value > 512:
del actual_params[key] |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
<|fim_middle|>
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | del actual_params[key] |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
<|fim_middle|>
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key] |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
<|fim_middle|>
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | del actual_params[key] |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
<|fim_middle|>
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
<|fim_middle|>
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
<|fim_middle|>
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | del actual_params[key] |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
<|fim_middle|>
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | actual_params[key] = value # urlencode will encode it later |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
<|fim_middle|>
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | gravatar_url += '?' + params_encode |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
<|fim_middle|>
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | params = template.Variable(self.params).resolve(context) |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
<|fim_middle|>
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | params = {} |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
<|fim_middle|>
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | email = email_literal |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
<|fim_middle|>
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | email = template.Variable(self.email).resolve(context) |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
<|fim_middle|>
return GravatarURLNode(email, params)
<|fim▁end|> | if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name) |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
<|fim_middle|>
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | email = email[1:-1] |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
<|fim_middle|>
return GravatarURLNode(email, params)
<|fim▁end|> | raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name) |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def <|fim_middle|>(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | _build_gravatar_url |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def <|fim_middle|>(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | __init__ |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def <|fim_middle|>(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def get_gravatar_url(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | render |
<|file_name|>gravatar_tags.py<|end_file_name|><|fim▁begin|>import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http://www.gravatar.com/avatar/'
DEFAULT_PARAMS = \
{
# api_key: (gravatar_key, value),
'size': ('s', 80), # value is in [1,512]
'rating': ('r', 'g'), # 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().encode('utf-8')
if not EMAIL_RE.match(email):
return ''
email_hash = hashlib.md5(email).hexdigest()
# step 2a: build a canonized parameters dictionary
if not type(params).__name__ == 'dict':
params = params.__dict__
actual_params = {}
default_keys = DEFAULT_PARAMS.keys()
for key, value in params.items():
if key in default_keys:
k, default_value = DEFAULT_PARAMS[key]
# skip parameters whose values are defaults,
# assume these values are mirroring Gravatar's defaults
if value != default_value:
actual_params[k] = value
# step 2b: validate the canonized parameters dictionary
# silently drop parameter when the value is not valid
for key, value in actual_params.items():
if key == 's':
if value < 1 or value > 512:
del actual_params[key]
elif key == 'r':
if value.lower() not in ('g', 'pg', 'r', 'x'):
del actual_params[key]
# except when the parameter key is 'd': replace with 'identicon'
elif key == 'd':
if value.lower() not in ('identicon', 'monsterid', 'wavatar', '404'):
if not URL_RE.match(value): # if not a valid URI
del actual_params[key]
else: # valid URI, encode it
actual_params[key] = value # urlencode will encode it later
# step 3: encode params
params_encode = urllib.urlencode(actual_params)
# step 4: form the gravatar url
gravatar_url = GRAVATAR_URL_PREFIX + email_hash
if params_encode:
gravatar_url += '?' + params_encode
return gravatar_url
class GravatarURLNode(template.Node):
def __init__(self, email, params):
self.email = email
self.params = params
def render(self, context):
try:
if self.params:
params = template.Variable(self.params).resolve(context)
else:
params = {}
# try matching an address string literal
email_literal = self.email.strip().lower()
if EMAIL_RE.match(email_literal):
email = email_literal
# treat as a variable
else:
email = template.Variable(self.email).resolve(context)
except template.VariableDoesNotExist:
return ''
# now, we generate the gravatar url
return _build_gravatar_url(email, params)
@register.tag(name="gravatar_url")
def <|fim_middle|>(parser, token):
"""For template tag: {% gravatar_url <email> <params> %}
Where <params> is an object or a dictionary (variable), and <email>
is a string object (variable) or a string (literal).
"""
try:
tag_name, email, params = token.split_contents()
except ValueError:
try:
tag_name, email = token.split_contents()
params = None
except ValueError:
raise template.TemplateSyntaxError('%r tag requires one or two arguments.' %
token.contents.split()[0])
# if email is quoted, parse as a literal string
if email[0] in ('"', "'") or email[-1] in ('"', "'"):
if email[0] == email[-1]:
email = email[1:-1]
else:
raise template.TemplateSyntaxError(
"%r tag's first argument is in unbalanced quotes." % tag_name)
return GravatarURLNode(email, params)
<|fim▁end|> | get_gravatar_url |
<|file_name|>tpl-py-0001.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
####################################
#
# --- TEXTPATGEN TEMPLATE ---
#<|fim▁hole|>
import sys
sys.stdout.write('####################################\n')
sys.stdout.write('#\n')
sys.stdout.write('# -- TEXTPATGEN GENERATED FILE --\n')
sys.stdout.write('#\n')
sys.stdout.write('# -- Created from a Python script.\n')
sys.stdout.write('#\n')
sys.stdout.write("####################################\n")
num=0
for length in range(0, 16):
for width in range(0, 15):
sys.stdout.write('X-%04X ' % num)
num=num+1
width=width+1
length=length+1
sys.stdout.write('X-%04X\n' % num)
num=num+1
sys.stdout.write('# -- End of file.\n');
sys.stdout.flush()<|fim▁end|> | # Users can change the output by editing
# this file directly.
#
#################################### |
<|file_name|>script.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | ../../../../../../../share/pyshared/orca/scripts/apps/nautilus/script.py |
<|file_name|>user.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
gateway tests - Users
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import unittest
import omero
import gatewaytest.library as lib
from omero.gateway.scripts import dbhelpers
class UserTest (lib.GTest):
def testUsers (self):
self.loginAsUser()
# Try reconnecting without disconnect
self._has_connected = False
self.doConnect()
self.loginAsAuthor()
self.loginAsAdmin()
def testSaveAs (self):
for u in (self.AUTHOR, self.ADMIN):
# Test image should be owned by author
self.loginAsAuthor()
image = self.getTestImage()
ownername = image.getOwnerOmeName()
# Now login as author or admin
self.doLogin(u)
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
image = self.getTestImage()
self.assertEqual(ownername, self.AUTHOR.name)
# Create some object
param = omero.sys.Parameters()
param.map = {'ns': omero.rtypes.rstring('weblitz.UserTest.testSaveAs')}
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
self.gateway.SERVICE_OPTS.setOmeroGroup()
ann = omero.gateway.CommentAnnotationWrapper(conn=self.gateway)
ann.setNs(param.map['ns'].val)
ann.setValue('foo')
ann.saveAs(image.getDetails())
# Annotations are owned by author
self.loginAsAuthor()
try:<|fim▁hole|> finally:
self.gateway.getUpdateService().deleteObject(ann._obj)
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
def testCrossGroupSave (self):
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
g = d.getDetails().getGroup()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g._obj])
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
# make sure the group is groupwrite enabled
perms = str(d.getDetails().getGroup().getDetails().permissions)
admin.changePermissions(g._obj, omero.model.PermissionsI('rwrw--'))
d = self.getTestDataset()
g = d.getDetails().getGroup()
self.assert_(g.getDetails().permissions.isGroupWrite())
self.loginAsUser()
# User is now a member of the group to which testDataset belongs, which has groupWrite==True
# But the default group for User is diferent
try:
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
n = d.getName()
d.setName(n+'_1')
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n+'_1')
d.setName(n)
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n)
finally:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
# Revert group permissions and remove user from group
admin.changePermissions(g._obj, omero.model.PermissionsI(perms))
admin.removeGroups(omero.model.ExperimenterI(uid, False), [g._obj])
def testCrossGroupRead (self):
self.loginAsAuthor()
u = self.gateway.getUpdateService()
p = self.getTestProject()
self.assertEqual(str(p.getDetails().permissions)[4], '-')
d = p.getDetails()
g = d.getGroup()
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assert_(not g.getId() in self.gateway.getEventContext().memberOfGroups)
self.assertEqual(self.gateway.getObject('project', p.getId()), None)
def testGroupOverObjPermissions (self):
""" Object accesss must be dependent only of group permissions """
ns = 'omero.test.ns'
# Author
self.loginAsAuthor()
# create group with rw----
# create project and annotation in that group
p = dbhelpers.ProjectEntry('testAnnotationPermissions', None, create_group='testAnnotationPermissions', group_perms='rw----')
try:
p = p.create(self.gateway)
except dbhelpers.BadGroupPermissionsException:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(admin.lookupGroup('testAnnotationPermissions'), omero.model.PermissionsI('rw----'))
self.loginAsAuthor()
p = p.create(self.gateway)
pid = p.getId()
g = p.getDetails().getGroup()._obj
try:
# Admin
# add User to group
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g])
# User
# try to read project and annotation, which fails
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertEqual(self.gateway.getObject('project', pid), None)
# Admin
# Chmod project to rwrw--
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(g, omero.model.PermissionsI('rwrw--'))
# Author
# check project has proper permissions
self.loginAsAuthor()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
pa = self.gateway.getObject('project', pid)
self.assertNotEqual(pa, None)
# User
# read project and annotation
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertNotEqual(self.gateway.getObject('project', pid), None)
finally:
self.loginAsAuthor()
handle = self.gateway.deleteObjects('Project', [p.getId()], deleteAnns=True, deleteChildren=True)
self.waitOnCmd(self.gateway.c, handle)
if __name__ == '__main__':
unittest.main()<|fim▁end|> | anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 1)
self.assertEqual(omero.gateway.CommentAnnotationWrapper(self.gateway, anns[0]).getOwnerOmeName(), self.AUTHOR.name) |
<|file_name|>user.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
gateway tests - Users
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import unittest
import omero
import gatewaytest.library as lib
from omero.gateway.scripts import dbhelpers
class UserTest (lib.GTest):
<|fim_middle|>
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | def testUsers (self):
self.loginAsUser()
# Try reconnecting without disconnect
self._has_connected = False
self.doConnect()
self.loginAsAuthor()
self.loginAsAdmin()
def testSaveAs (self):
for u in (self.AUTHOR, self.ADMIN):
# Test image should be owned by author
self.loginAsAuthor()
image = self.getTestImage()
ownername = image.getOwnerOmeName()
# Now login as author or admin
self.doLogin(u)
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
image = self.getTestImage()
self.assertEqual(ownername, self.AUTHOR.name)
# Create some object
param = omero.sys.Parameters()
param.map = {'ns': omero.rtypes.rstring('weblitz.UserTest.testSaveAs')}
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
self.gateway.SERVICE_OPTS.setOmeroGroup()
ann = omero.gateway.CommentAnnotationWrapper(conn=self.gateway)
ann.setNs(param.map['ns'].val)
ann.setValue('foo')
ann.saveAs(image.getDetails())
# Annotations are owned by author
self.loginAsAuthor()
try:
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 1)
self.assertEqual(omero.gateway.CommentAnnotationWrapper(self.gateway, anns[0]).getOwnerOmeName(), self.AUTHOR.name)
finally:
self.gateway.getUpdateService().deleteObject(ann._obj)
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
def testCrossGroupSave (self):
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
g = d.getDetails().getGroup()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g._obj])
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
# make sure the group is groupwrite enabled
perms = str(d.getDetails().getGroup().getDetails().permissions)
admin.changePermissions(g._obj, omero.model.PermissionsI('rwrw--'))
d = self.getTestDataset()
g = d.getDetails().getGroup()
self.assert_(g.getDetails().permissions.isGroupWrite())
self.loginAsUser()
# User is now a member of the group to which testDataset belongs, which has groupWrite==True
# But the default group for User is diferent
try:
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
n = d.getName()
d.setName(n+'_1')
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n+'_1')
d.setName(n)
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n)
finally:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
# Revert group permissions and remove user from group
admin.changePermissions(g._obj, omero.model.PermissionsI(perms))
admin.removeGroups(omero.model.ExperimenterI(uid, False), [g._obj])
def testCrossGroupRead (self):
self.loginAsAuthor()
u = self.gateway.getUpdateService()
p = self.getTestProject()
self.assertEqual(str(p.getDetails().permissions)[4], '-')
d = p.getDetails()
g = d.getGroup()
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assert_(not g.getId() in self.gateway.getEventContext().memberOfGroups)
self.assertEqual(self.gateway.getObject('project', p.getId()), None)
def testGroupOverObjPermissions (self):
""" Object accesss must be dependent only of group permissions """
ns = 'omero.test.ns'
# Author
self.loginAsAuthor()
# create group with rw----
# create project and annotation in that group
p = dbhelpers.ProjectEntry('testAnnotationPermissions', None, create_group='testAnnotationPermissions', group_perms='rw----')
try:
p = p.create(self.gateway)
except dbhelpers.BadGroupPermissionsException:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(admin.lookupGroup('testAnnotationPermissions'), omero.model.PermissionsI('rw----'))
self.loginAsAuthor()
p = p.create(self.gateway)
pid = p.getId()
g = p.getDetails().getGroup()._obj
try:
# Admin
# add User to group
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g])
# User
# try to read project and annotation, which fails
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertEqual(self.gateway.getObject('project', pid), None)
# Admin
# Chmod project to rwrw--
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(g, omero.model.PermissionsI('rwrw--'))
# Author
# check project has proper permissions
self.loginAsAuthor()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
pa = self.gateway.getObject('project', pid)
self.assertNotEqual(pa, None)
# User
# read project and annotation
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertNotEqual(self.gateway.getObject('project', pid), None)
finally:
self.loginAsAuthor()
handle = self.gateway.deleteObjects('Project', [p.getId()], deleteAnns=True, deleteChildren=True)
self.waitOnCmd(self.gateway.c, handle) |
<|file_name|>user.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
gateway tests - Users
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import unittest
import omero
import gatewaytest.library as lib
from omero.gateway.scripts import dbhelpers
class UserTest (lib.GTest):
def testUsers (self):
<|fim_middle|>
def testSaveAs (self):
for u in (self.AUTHOR, self.ADMIN):
# Test image should be owned by author
self.loginAsAuthor()
image = self.getTestImage()
ownername = image.getOwnerOmeName()
# Now login as author or admin
self.doLogin(u)
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
image = self.getTestImage()
self.assertEqual(ownername, self.AUTHOR.name)
# Create some object
param = omero.sys.Parameters()
param.map = {'ns': omero.rtypes.rstring('weblitz.UserTest.testSaveAs')}
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
self.gateway.SERVICE_OPTS.setOmeroGroup()
ann = omero.gateway.CommentAnnotationWrapper(conn=self.gateway)
ann.setNs(param.map['ns'].val)
ann.setValue('foo')
ann.saveAs(image.getDetails())
# Annotations are owned by author
self.loginAsAuthor()
try:
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 1)
self.assertEqual(omero.gateway.CommentAnnotationWrapper(self.gateway, anns[0]).getOwnerOmeName(), self.AUTHOR.name)
finally:
self.gateway.getUpdateService().deleteObject(ann._obj)
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
def testCrossGroupSave (self):
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
g = d.getDetails().getGroup()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g._obj])
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
# make sure the group is groupwrite enabled
perms = str(d.getDetails().getGroup().getDetails().permissions)
admin.changePermissions(g._obj, omero.model.PermissionsI('rwrw--'))
d = self.getTestDataset()
g = d.getDetails().getGroup()
self.assert_(g.getDetails().permissions.isGroupWrite())
self.loginAsUser()
# User is now a member of the group to which testDataset belongs, which has groupWrite==True
# But the default group for User is diferent
try:
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
n = d.getName()
d.setName(n+'_1')
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n+'_1')
d.setName(n)
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n)
finally:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
# Revert group permissions and remove user from group
admin.changePermissions(g._obj, omero.model.PermissionsI(perms))
admin.removeGroups(omero.model.ExperimenterI(uid, False), [g._obj])
def testCrossGroupRead (self):
self.loginAsAuthor()
u = self.gateway.getUpdateService()
p = self.getTestProject()
self.assertEqual(str(p.getDetails().permissions)[4], '-')
d = p.getDetails()
g = d.getGroup()
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assert_(not g.getId() in self.gateway.getEventContext().memberOfGroups)
self.assertEqual(self.gateway.getObject('project', p.getId()), None)
def testGroupOverObjPermissions (self):
""" Object accesss must be dependent only of group permissions """
ns = 'omero.test.ns'
# Author
self.loginAsAuthor()
# create group with rw----
# create project and annotation in that group
p = dbhelpers.ProjectEntry('testAnnotationPermissions', None, create_group='testAnnotationPermissions', group_perms='rw----')
try:
p = p.create(self.gateway)
except dbhelpers.BadGroupPermissionsException:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(admin.lookupGroup('testAnnotationPermissions'), omero.model.PermissionsI('rw----'))
self.loginAsAuthor()
p = p.create(self.gateway)
pid = p.getId()
g = p.getDetails().getGroup()._obj
try:
# Admin
# add User to group
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g])
# User
# try to read project and annotation, which fails
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertEqual(self.gateway.getObject('project', pid), None)
# Admin
# Chmod project to rwrw--
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(g, omero.model.PermissionsI('rwrw--'))
# Author
# check project has proper permissions
self.loginAsAuthor()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
pa = self.gateway.getObject('project', pid)
self.assertNotEqual(pa, None)
# User
# read project and annotation
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertNotEqual(self.gateway.getObject('project', pid), None)
finally:
self.loginAsAuthor()
handle = self.gateway.deleteObjects('Project', [p.getId()], deleteAnns=True, deleteChildren=True)
self.waitOnCmd(self.gateway.c, handle)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | self.loginAsUser()
# Try reconnecting without disconnect
self._has_connected = False
self.doConnect()
self.loginAsAuthor()
self.loginAsAdmin() |
<|file_name|>user.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
gateway tests - Users
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import unittest
import omero
import gatewaytest.library as lib
from omero.gateway.scripts import dbhelpers
class UserTest (lib.GTest):
def testUsers (self):
self.loginAsUser()
# Try reconnecting without disconnect
self._has_connected = False
self.doConnect()
self.loginAsAuthor()
self.loginAsAdmin()
def testSaveAs (self):
<|fim_middle|>
def testCrossGroupSave (self):
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
g = d.getDetails().getGroup()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g._obj])
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
# make sure the group is groupwrite enabled
perms = str(d.getDetails().getGroup().getDetails().permissions)
admin.changePermissions(g._obj, omero.model.PermissionsI('rwrw--'))
d = self.getTestDataset()
g = d.getDetails().getGroup()
self.assert_(g.getDetails().permissions.isGroupWrite())
self.loginAsUser()
# User is now a member of the group to which testDataset belongs, which has groupWrite==True
# But the default group for User is diferent
try:
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
n = d.getName()
d.setName(n+'_1')
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n+'_1')
d.setName(n)
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n)
finally:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
# Revert group permissions and remove user from group
admin.changePermissions(g._obj, omero.model.PermissionsI(perms))
admin.removeGroups(omero.model.ExperimenterI(uid, False), [g._obj])
def testCrossGroupRead (self):
self.loginAsAuthor()
u = self.gateway.getUpdateService()
p = self.getTestProject()
self.assertEqual(str(p.getDetails().permissions)[4], '-')
d = p.getDetails()
g = d.getGroup()
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assert_(not g.getId() in self.gateway.getEventContext().memberOfGroups)
self.assertEqual(self.gateway.getObject('project', p.getId()), None)
def testGroupOverObjPermissions (self):
""" Object accesss must be dependent only of group permissions """
ns = 'omero.test.ns'
# Author
self.loginAsAuthor()
# create group with rw----
# create project and annotation in that group
p = dbhelpers.ProjectEntry('testAnnotationPermissions', None, create_group='testAnnotationPermissions', group_perms='rw----')
try:
p = p.create(self.gateway)
except dbhelpers.BadGroupPermissionsException:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(admin.lookupGroup('testAnnotationPermissions'), omero.model.PermissionsI('rw----'))
self.loginAsAuthor()
p = p.create(self.gateway)
pid = p.getId()
g = p.getDetails().getGroup()._obj
try:
# Admin
# add User to group
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g])
# User
# try to read project and annotation, which fails
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertEqual(self.gateway.getObject('project', pid), None)
# Admin
# Chmod project to rwrw--
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(g, omero.model.PermissionsI('rwrw--'))
# Author
# check project has proper permissions
self.loginAsAuthor()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
pa = self.gateway.getObject('project', pid)
self.assertNotEqual(pa, None)
# User
# read project and annotation
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertNotEqual(self.gateway.getObject('project', pid), None)
finally:
self.loginAsAuthor()
handle = self.gateway.deleteObjects('Project', [p.getId()], deleteAnns=True, deleteChildren=True)
self.waitOnCmd(self.gateway.c, handle)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | for u in (self.AUTHOR, self.ADMIN):
# Test image should be owned by author
self.loginAsAuthor()
image = self.getTestImage()
ownername = image.getOwnerOmeName()
# Now login as author or admin
self.doLogin(u)
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
image = self.getTestImage()
self.assertEqual(ownername, self.AUTHOR.name)
# Create some object
param = omero.sys.Parameters()
param.map = {'ns': omero.rtypes.rstring('weblitz.UserTest.testSaveAs')}
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
self.gateway.SERVICE_OPTS.setOmeroGroup()
ann = omero.gateway.CommentAnnotationWrapper(conn=self.gateway)
ann.setNs(param.map['ns'].val)
ann.setValue('foo')
ann.saveAs(image.getDetails())
# Annotations are owned by author
self.loginAsAuthor()
try:
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 1)
self.assertEqual(omero.gateway.CommentAnnotationWrapper(self.gateway, anns[0]).getOwnerOmeName(), self.AUTHOR.name)
finally:
self.gateway.getUpdateService().deleteObject(ann._obj)
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0) |
<|file_name|>user.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
gateway tests - Users
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import unittest
import omero
import gatewaytest.library as lib
from omero.gateway.scripts import dbhelpers
class UserTest (lib.GTest):
def testUsers (self):
self.loginAsUser()
# Try reconnecting without disconnect
self._has_connected = False
self.doConnect()
self.loginAsAuthor()
self.loginAsAdmin()
def testSaveAs (self):
for u in (self.AUTHOR, self.ADMIN):
# Test image should be owned by author
self.loginAsAuthor()
image = self.getTestImage()
ownername = image.getOwnerOmeName()
# Now login as author or admin
self.doLogin(u)
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
image = self.getTestImage()
self.assertEqual(ownername, self.AUTHOR.name)
# Create some object
param = omero.sys.Parameters()
param.map = {'ns': omero.rtypes.rstring('weblitz.UserTest.testSaveAs')}
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
self.gateway.SERVICE_OPTS.setOmeroGroup()
ann = omero.gateway.CommentAnnotationWrapper(conn=self.gateway)
ann.setNs(param.map['ns'].val)
ann.setValue('foo')
ann.saveAs(image.getDetails())
# Annotations are owned by author
self.loginAsAuthor()
try:
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 1)
self.assertEqual(omero.gateway.CommentAnnotationWrapper(self.gateway, anns[0]).getOwnerOmeName(), self.AUTHOR.name)
finally:
self.gateway.getUpdateService().deleteObject(ann._obj)
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
def testCrossGroupSave (self):
<|fim_middle|>
def testCrossGroupRead (self):
self.loginAsAuthor()
u = self.gateway.getUpdateService()
p = self.getTestProject()
self.assertEqual(str(p.getDetails().permissions)[4], '-')
d = p.getDetails()
g = d.getGroup()
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assert_(not g.getId() in self.gateway.getEventContext().memberOfGroups)
self.assertEqual(self.gateway.getObject('project', p.getId()), None)
def testGroupOverObjPermissions (self):
""" Object accesss must be dependent only of group permissions """
ns = 'omero.test.ns'
# Author
self.loginAsAuthor()
# create group with rw----
# create project and annotation in that group
p = dbhelpers.ProjectEntry('testAnnotationPermissions', None, create_group='testAnnotationPermissions', group_perms='rw----')
try:
p = p.create(self.gateway)
except dbhelpers.BadGroupPermissionsException:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(admin.lookupGroup('testAnnotationPermissions'), omero.model.PermissionsI('rw----'))
self.loginAsAuthor()
p = p.create(self.gateway)
pid = p.getId()
g = p.getDetails().getGroup()._obj
try:
# Admin
# add User to group
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g])
# User
# try to read project and annotation, which fails
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertEqual(self.gateway.getObject('project', pid), None)
# Admin
# Chmod project to rwrw--
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(g, omero.model.PermissionsI('rwrw--'))
# Author
# check project has proper permissions
self.loginAsAuthor()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
pa = self.gateway.getObject('project', pid)
self.assertNotEqual(pa, None)
# User
# read project and annotation
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertNotEqual(self.gateway.getObject('project', pid), None)
finally:
self.loginAsAuthor()
handle = self.gateway.deleteObjects('Project', [p.getId()], deleteAnns=True, deleteChildren=True)
self.waitOnCmd(self.gateway.c, handle)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
g = d.getDetails().getGroup()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g._obj])
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
# make sure the group is groupwrite enabled
perms = str(d.getDetails().getGroup().getDetails().permissions)
admin.changePermissions(g._obj, omero.model.PermissionsI('rwrw--'))
d = self.getTestDataset()
g = d.getDetails().getGroup()
self.assert_(g.getDetails().permissions.isGroupWrite())
self.loginAsUser()
# User is now a member of the group to which testDataset belongs, which has groupWrite==True
# But the default group for User is diferent
try:
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
n = d.getName()
d.setName(n+'_1')
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n+'_1')
d.setName(n)
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n)
finally:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
# Revert group permissions and remove user from group
admin.changePermissions(g._obj, omero.model.PermissionsI(perms))
admin.removeGroups(omero.model.ExperimenterI(uid, False), [g._obj]) |
<|file_name|>user.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
gateway tests - Users
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import unittest
import omero
import gatewaytest.library as lib
from omero.gateway.scripts import dbhelpers
class UserTest (lib.GTest):
def testUsers (self):
self.loginAsUser()
# Try reconnecting without disconnect
self._has_connected = False
self.doConnect()
self.loginAsAuthor()
self.loginAsAdmin()
def testSaveAs (self):
for u in (self.AUTHOR, self.ADMIN):
# Test image should be owned by author
self.loginAsAuthor()
image = self.getTestImage()
ownername = image.getOwnerOmeName()
# Now login as author or admin
self.doLogin(u)
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
image = self.getTestImage()
self.assertEqual(ownername, self.AUTHOR.name)
# Create some object
param = omero.sys.Parameters()
param.map = {'ns': omero.rtypes.rstring('weblitz.UserTest.testSaveAs')}
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
self.gateway.SERVICE_OPTS.setOmeroGroup()
ann = omero.gateway.CommentAnnotationWrapper(conn=self.gateway)
ann.setNs(param.map['ns'].val)
ann.setValue('foo')
ann.saveAs(image.getDetails())
# Annotations are owned by author
self.loginAsAuthor()
try:
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 1)
self.assertEqual(omero.gateway.CommentAnnotationWrapper(self.gateway, anns[0]).getOwnerOmeName(), self.AUTHOR.name)
finally:
self.gateway.getUpdateService().deleteObject(ann._obj)
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
def testCrossGroupSave (self):
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
g = d.getDetails().getGroup()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g._obj])
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
# make sure the group is groupwrite enabled
perms = str(d.getDetails().getGroup().getDetails().permissions)
admin.changePermissions(g._obj, omero.model.PermissionsI('rwrw--'))
d = self.getTestDataset()
g = d.getDetails().getGroup()
self.assert_(g.getDetails().permissions.isGroupWrite())
self.loginAsUser()
# User is now a member of the group to which testDataset belongs, which has groupWrite==True
# But the default group for User is diferent
try:
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
n = d.getName()
d.setName(n+'_1')
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n+'_1')
d.setName(n)
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n)
finally:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
# Revert group permissions and remove user from group
admin.changePermissions(g._obj, omero.model.PermissionsI(perms))
admin.removeGroups(omero.model.ExperimenterI(uid, False), [g._obj])
def testCrossGroupRead (self):
<|fim_middle|>
def testGroupOverObjPermissions (self):
""" Object accesss must be dependent only of group permissions """
ns = 'omero.test.ns'
# Author
self.loginAsAuthor()
# create group with rw----
# create project and annotation in that group
p = dbhelpers.ProjectEntry('testAnnotationPermissions', None, create_group='testAnnotationPermissions', group_perms='rw----')
try:
p = p.create(self.gateway)
except dbhelpers.BadGroupPermissionsException:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(admin.lookupGroup('testAnnotationPermissions'), omero.model.PermissionsI('rw----'))
self.loginAsAuthor()
p = p.create(self.gateway)
pid = p.getId()
g = p.getDetails().getGroup()._obj
try:
# Admin
# add User to group
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g])
# User
# try to read project and annotation, which fails
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertEqual(self.gateway.getObject('project', pid), None)
# Admin
# Chmod project to rwrw--
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(g, omero.model.PermissionsI('rwrw--'))
# Author
# check project has proper permissions
self.loginAsAuthor()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
pa = self.gateway.getObject('project', pid)
self.assertNotEqual(pa, None)
# User
# read project and annotation
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertNotEqual(self.gateway.getObject('project', pid), None)
finally:
self.loginAsAuthor()
handle = self.gateway.deleteObjects('Project', [p.getId()], deleteAnns=True, deleteChildren=True)
self.waitOnCmd(self.gateway.c, handle)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | self.loginAsAuthor()
u = self.gateway.getUpdateService()
p = self.getTestProject()
self.assertEqual(str(p.getDetails().permissions)[4], '-')
d = p.getDetails()
g = d.getGroup()
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assert_(not g.getId() in self.gateway.getEventContext().memberOfGroups)
self.assertEqual(self.gateway.getObject('project', p.getId()), None) |
<|file_name|>user.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
gateway tests - Users
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import unittest
import omero
import gatewaytest.library as lib
from omero.gateway.scripts import dbhelpers
class UserTest (lib.GTest):
def testUsers (self):
self.loginAsUser()
# Try reconnecting without disconnect
self._has_connected = False
self.doConnect()
self.loginAsAuthor()
self.loginAsAdmin()
def testSaveAs (self):
for u in (self.AUTHOR, self.ADMIN):
# Test image should be owned by author
self.loginAsAuthor()
image = self.getTestImage()
ownername = image.getOwnerOmeName()
# Now login as author or admin
self.doLogin(u)
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
image = self.getTestImage()
self.assertEqual(ownername, self.AUTHOR.name)
# Create some object
param = omero.sys.Parameters()
param.map = {'ns': omero.rtypes.rstring('weblitz.UserTest.testSaveAs')}
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
self.gateway.SERVICE_OPTS.setOmeroGroup()
ann = omero.gateway.CommentAnnotationWrapper(conn=self.gateway)
ann.setNs(param.map['ns'].val)
ann.setValue('foo')
ann.saveAs(image.getDetails())
# Annotations are owned by author
self.loginAsAuthor()
try:
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 1)
self.assertEqual(omero.gateway.CommentAnnotationWrapper(self.gateway, anns[0]).getOwnerOmeName(), self.AUTHOR.name)
finally:
self.gateway.getUpdateService().deleteObject(ann._obj)
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
def testCrossGroupSave (self):
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
g = d.getDetails().getGroup()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g._obj])
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
# make sure the group is groupwrite enabled
perms = str(d.getDetails().getGroup().getDetails().permissions)
admin.changePermissions(g._obj, omero.model.PermissionsI('rwrw--'))
d = self.getTestDataset()
g = d.getDetails().getGroup()
self.assert_(g.getDetails().permissions.isGroupWrite())
self.loginAsUser()
# User is now a member of the group to which testDataset belongs, which has groupWrite==True
# But the default group for User is diferent
try:
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
n = d.getName()
d.setName(n+'_1')
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n+'_1')
d.setName(n)
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n)
finally:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
# Revert group permissions and remove user from group
admin.changePermissions(g._obj, omero.model.PermissionsI(perms))
admin.removeGroups(omero.model.ExperimenterI(uid, False), [g._obj])
def testCrossGroupRead (self):
self.loginAsAuthor()
u = self.gateway.getUpdateService()
p = self.getTestProject()
self.assertEqual(str(p.getDetails().permissions)[4], '-')
d = p.getDetails()
g = d.getGroup()
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assert_(not g.getId() in self.gateway.getEventContext().memberOfGroups)
self.assertEqual(self.gateway.getObject('project', p.getId()), None)
def testGroupOverObjPermissions (self):
<|fim_middle|>
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | """ Object accesss must be dependent only of group permissions """
ns = 'omero.test.ns'
# Author
self.loginAsAuthor()
# create group with rw----
# create project and annotation in that group
p = dbhelpers.ProjectEntry('testAnnotationPermissions', None, create_group='testAnnotationPermissions', group_perms='rw----')
try:
p = p.create(self.gateway)
except dbhelpers.BadGroupPermissionsException:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(admin.lookupGroup('testAnnotationPermissions'), omero.model.PermissionsI('rw----'))
self.loginAsAuthor()
p = p.create(self.gateway)
pid = p.getId()
g = p.getDetails().getGroup()._obj
try:
# Admin
# add User to group
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g])
# User
# try to read project and annotation, which fails
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertEqual(self.gateway.getObject('project', pid), None)
# Admin
# Chmod project to rwrw--
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(g, omero.model.PermissionsI('rwrw--'))
# Author
# check project has proper permissions
self.loginAsAuthor()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
pa = self.gateway.getObject('project', pid)
self.assertNotEqual(pa, None)
# User
# read project and annotation
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertNotEqual(self.gateway.getObject('project', pid), None)
finally:
self.loginAsAuthor()
handle = self.gateway.deleteObjects('Project', [p.getId()], deleteAnns=True, deleteChildren=True)
self.waitOnCmd(self.gateway.c, handle) |
<|file_name|>user.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
gateway tests - Users
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import unittest
import omero
import gatewaytest.library as lib
from omero.gateway.scripts import dbhelpers
class UserTest (lib.GTest):
def testUsers (self):
self.loginAsUser()
# Try reconnecting without disconnect
self._has_connected = False
self.doConnect()
self.loginAsAuthor()
self.loginAsAdmin()
def testSaveAs (self):
for u in (self.AUTHOR, self.ADMIN):
# Test image should be owned by author
self.loginAsAuthor()
image = self.getTestImage()
ownername = image.getOwnerOmeName()
# Now login as author or admin
self.doLogin(u)
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
image = self.getTestImage()
self.assertEqual(ownername, self.AUTHOR.name)
# Create some object
param = omero.sys.Parameters()
param.map = {'ns': omero.rtypes.rstring('weblitz.UserTest.testSaveAs')}
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
self.gateway.SERVICE_OPTS.setOmeroGroup()
ann = omero.gateway.CommentAnnotationWrapper(conn=self.gateway)
ann.setNs(param.map['ns'].val)
ann.setValue('foo')
ann.saveAs(image.getDetails())
# Annotations are owned by author
self.loginAsAuthor()
try:
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 1)
self.assertEqual(omero.gateway.CommentAnnotationWrapper(self.gateway, anns[0]).getOwnerOmeName(), self.AUTHOR.name)
finally:
self.gateway.getUpdateService().deleteObject(ann._obj)
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
def testCrossGroupSave (self):
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
g = d.getDetails().getGroup()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g._obj])
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
# make sure the group is groupwrite enabled
perms = str(d.getDetails().getGroup().getDetails().permissions)
admin.changePermissions(g._obj, omero.model.PermissionsI('rwrw--'))
d = self.getTestDataset()
g = d.getDetails().getGroup()
self.assert_(g.getDetails().permissions.isGroupWrite())
self.loginAsUser()
# User is now a member of the group to which testDataset belongs, which has groupWrite==True
# But the default group for User is diferent
try:
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
n = d.getName()
d.setName(n+'_1')
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n+'_1')
d.setName(n)
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n)
finally:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
# Revert group permissions and remove user from group
admin.changePermissions(g._obj, omero.model.PermissionsI(perms))
admin.removeGroups(omero.model.ExperimenterI(uid, False), [g._obj])
def testCrossGroupRead (self):
self.loginAsAuthor()
u = self.gateway.getUpdateService()
p = self.getTestProject()
self.assertEqual(str(p.getDetails().permissions)[4], '-')
d = p.getDetails()
g = d.getGroup()
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assert_(not g.getId() in self.gateway.getEventContext().memberOfGroups)
self.assertEqual(self.gateway.getObject('project', p.getId()), None)
def testGroupOverObjPermissions (self):
""" Object accesss must be dependent only of group permissions """
ns = 'omero.test.ns'
# Author
self.loginAsAuthor()
# create group with rw----
# create project and annotation in that group
p = dbhelpers.ProjectEntry('testAnnotationPermissions', None, create_group='testAnnotationPermissions', group_perms='rw----')
try:
p = p.create(self.gateway)
except dbhelpers.BadGroupPermissionsException:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(admin.lookupGroup('testAnnotationPermissions'), omero.model.PermissionsI('rw----'))
self.loginAsAuthor()
p = p.create(self.gateway)
pid = p.getId()
g = p.getDetails().getGroup()._obj
try:
# Admin
# add User to group
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g])
# User
# try to read project and annotation, which fails
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertEqual(self.gateway.getObject('project', pid), None)
# Admin
# Chmod project to rwrw--
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(g, omero.model.PermissionsI('rwrw--'))
# Author
# check project has proper permissions
self.loginAsAuthor()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
pa = self.gateway.getObject('project', pid)
self.assertNotEqual(pa, None)
# User
# read project and annotation
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertNotEqual(self.gateway.getObject('project', pid), None)
finally:
self.loginAsAuthor()
handle = self.gateway.deleteObjects('Project', [p.getId()], deleteAnns=True, deleteChildren=True)
self.waitOnCmd(self.gateway.c, handle)
if __name__ == '__main__':
<|fim_middle|>
<|fim▁end|> | unittest.main() |
<|file_name|>user.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
gateway tests - Users
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import unittest
import omero
import gatewaytest.library as lib
from omero.gateway.scripts import dbhelpers
class UserTest (lib.GTest):
def <|fim_middle|> (self):
self.loginAsUser()
# Try reconnecting without disconnect
self._has_connected = False
self.doConnect()
self.loginAsAuthor()
self.loginAsAdmin()
def testSaveAs (self):
for u in (self.AUTHOR, self.ADMIN):
# Test image should be owned by author
self.loginAsAuthor()
image = self.getTestImage()
ownername = image.getOwnerOmeName()
# Now login as author or admin
self.doLogin(u)
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
image = self.getTestImage()
self.assertEqual(ownername, self.AUTHOR.name)
# Create some object
param = omero.sys.Parameters()
param.map = {'ns': omero.rtypes.rstring('weblitz.UserTest.testSaveAs')}
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
self.gateway.SERVICE_OPTS.setOmeroGroup()
ann = omero.gateway.CommentAnnotationWrapper(conn=self.gateway)
ann.setNs(param.map['ns'].val)
ann.setValue('foo')
ann.saveAs(image.getDetails())
# Annotations are owned by author
self.loginAsAuthor()
try:
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 1)
self.assertEqual(omero.gateway.CommentAnnotationWrapper(self.gateway, anns[0]).getOwnerOmeName(), self.AUTHOR.name)
finally:
self.gateway.getUpdateService().deleteObject(ann._obj)
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
def testCrossGroupSave (self):
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
g = d.getDetails().getGroup()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g._obj])
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
# make sure the group is groupwrite enabled
perms = str(d.getDetails().getGroup().getDetails().permissions)
admin.changePermissions(g._obj, omero.model.PermissionsI('rwrw--'))
d = self.getTestDataset()
g = d.getDetails().getGroup()
self.assert_(g.getDetails().permissions.isGroupWrite())
self.loginAsUser()
# User is now a member of the group to which testDataset belongs, which has groupWrite==True
# But the default group for User is diferent
try:
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
n = d.getName()
d.setName(n+'_1')
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n+'_1')
d.setName(n)
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n)
finally:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
# Revert group permissions and remove user from group
admin.changePermissions(g._obj, omero.model.PermissionsI(perms))
admin.removeGroups(omero.model.ExperimenterI(uid, False), [g._obj])
def testCrossGroupRead (self):
self.loginAsAuthor()
u = self.gateway.getUpdateService()
p = self.getTestProject()
self.assertEqual(str(p.getDetails().permissions)[4], '-')
d = p.getDetails()
g = d.getGroup()
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assert_(not g.getId() in self.gateway.getEventContext().memberOfGroups)
self.assertEqual(self.gateway.getObject('project', p.getId()), None)
def testGroupOverObjPermissions (self):
""" Object accesss must be dependent only of group permissions """
ns = 'omero.test.ns'
# Author
self.loginAsAuthor()
# create group with rw----
# create project and annotation in that group
p = dbhelpers.ProjectEntry('testAnnotationPermissions', None, create_group='testAnnotationPermissions', group_perms='rw----')
try:
p = p.create(self.gateway)
except dbhelpers.BadGroupPermissionsException:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(admin.lookupGroup('testAnnotationPermissions'), omero.model.PermissionsI('rw----'))
self.loginAsAuthor()
p = p.create(self.gateway)
pid = p.getId()
g = p.getDetails().getGroup()._obj
try:
# Admin
# add User to group
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g])
# User
# try to read project and annotation, which fails
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertEqual(self.gateway.getObject('project', pid), None)
# Admin
# Chmod project to rwrw--
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(g, omero.model.PermissionsI('rwrw--'))
# Author
# check project has proper permissions
self.loginAsAuthor()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
pa = self.gateway.getObject('project', pid)
self.assertNotEqual(pa, None)
# User
# read project and annotation
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertNotEqual(self.gateway.getObject('project', pid), None)
finally:
self.loginAsAuthor()
handle = self.gateway.deleteObjects('Project', [p.getId()], deleteAnns=True, deleteChildren=True)
self.waitOnCmd(self.gateway.c, handle)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | testUsers |
<|file_name|>user.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
gateway tests - Users
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import unittest
import omero
import gatewaytest.library as lib
from omero.gateway.scripts import dbhelpers
class UserTest (lib.GTest):
def testUsers (self):
self.loginAsUser()
# Try reconnecting without disconnect
self._has_connected = False
self.doConnect()
self.loginAsAuthor()
self.loginAsAdmin()
def <|fim_middle|> (self):
for u in (self.AUTHOR, self.ADMIN):
# Test image should be owned by author
self.loginAsAuthor()
image = self.getTestImage()
ownername = image.getOwnerOmeName()
# Now login as author or admin
self.doLogin(u)
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
image = self.getTestImage()
self.assertEqual(ownername, self.AUTHOR.name)
# Create some object
param = omero.sys.Parameters()
param.map = {'ns': omero.rtypes.rstring('weblitz.UserTest.testSaveAs')}
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
self.gateway.SERVICE_OPTS.setOmeroGroup()
ann = omero.gateway.CommentAnnotationWrapper(conn=self.gateway)
ann.setNs(param.map['ns'].val)
ann.setValue('foo')
ann.saveAs(image.getDetails())
# Annotations are owned by author
self.loginAsAuthor()
try:
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 1)
self.assertEqual(omero.gateway.CommentAnnotationWrapper(self.gateway, anns[0]).getOwnerOmeName(), self.AUTHOR.name)
finally:
self.gateway.getUpdateService().deleteObject(ann._obj)
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
def testCrossGroupSave (self):
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
g = d.getDetails().getGroup()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g._obj])
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
# make sure the group is groupwrite enabled
perms = str(d.getDetails().getGroup().getDetails().permissions)
admin.changePermissions(g._obj, omero.model.PermissionsI('rwrw--'))
d = self.getTestDataset()
g = d.getDetails().getGroup()
self.assert_(g.getDetails().permissions.isGroupWrite())
self.loginAsUser()
# User is now a member of the group to which testDataset belongs, which has groupWrite==True
# But the default group for User is diferent
try:
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
n = d.getName()
d.setName(n+'_1')
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n+'_1')
d.setName(n)
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n)
finally:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
# Revert group permissions and remove user from group
admin.changePermissions(g._obj, omero.model.PermissionsI(perms))
admin.removeGroups(omero.model.ExperimenterI(uid, False), [g._obj])
def testCrossGroupRead (self):
self.loginAsAuthor()
u = self.gateway.getUpdateService()
p = self.getTestProject()
self.assertEqual(str(p.getDetails().permissions)[4], '-')
d = p.getDetails()
g = d.getGroup()
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assert_(not g.getId() in self.gateway.getEventContext().memberOfGroups)
self.assertEqual(self.gateway.getObject('project', p.getId()), None)
def testGroupOverObjPermissions (self):
""" Object accesss must be dependent only of group permissions """
ns = 'omero.test.ns'
# Author
self.loginAsAuthor()
# create group with rw----
# create project and annotation in that group
p = dbhelpers.ProjectEntry('testAnnotationPermissions', None, create_group='testAnnotationPermissions', group_perms='rw----')
try:
p = p.create(self.gateway)
except dbhelpers.BadGroupPermissionsException:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(admin.lookupGroup('testAnnotationPermissions'), omero.model.PermissionsI('rw----'))
self.loginAsAuthor()
p = p.create(self.gateway)
pid = p.getId()
g = p.getDetails().getGroup()._obj
try:
# Admin
# add User to group
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g])
# User
# try to read project and annotation, which fails
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertEqual(self.gateway.getObject('project', pid), None)
# Admin
# Chmod project to rwrw--
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(g, omero.model.PermissionsI('rwrw--'))
# Author
# check project has proper permissions
self.loginAsAuthor()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
pa = self.gateway.getObject('project', pid)
self.assertNotEqual(pa, None)
# User
# read project and annotation
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertNotEqual(self.gateway.getObject('project', pid), None)
finally:
self.loginAsAuthor()
handle = self.gateway.deleteObjects('Project', [p.getId()], deleteAnns=True, deleteChildren=True)
self.waitOnCmd(self.gateway.c, handle)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | testSaveAs |
<|file_name|>user.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
gateway tests - Users
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import unittest
import omero
import gatewaytest.library as lib
from omero.gateway.scripts import dbhelpers
class UserTest (lib.GTest):
def testUsers (self):
self.loginAsUser()
# Try reconnecting without disconnect
self._has_connected = False
self.doConnect()
self.loginAsAuthor()
self.loginAsAdmin()
def testSaveAs (self):
for u in (self.AUTHOR, self.ADMIN):
# Test image should be owned by author
self.loginAsAuthor()
image = self.getTestImage()
ownername = image.getOwnerOmeName()
# Now login as author or admin
self.doLogin(u)
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
image = self.getTestImage()
self.assertEqual(ownername, self.AUTHOR.name)
# Create some object
param = omero.sys.Parameters()
param.map = {'ns': omero.rtypes.rstring('weblitz.UserTest.testSaveAs')}
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
self.gateway.SERVICE_OPTS.setOmeroGroup()
ann = omero.gateway.CommentAnnotationWrapper(conn=self.gateway)
ann.setNs(param.map['ns'].val)
ann.setValue('foo')
ann.saveAs(image.getDetails())
# Annotations are owned by author
self.loginAsAuthor()
try:
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 1)
self.assertEqual(omero.gateway.CommentAnnotationWrapper(self.gateway, anns[0]).getOwnerOmeName(), self.AUTHOR.name)
finally:
self.gateway.getUpdateService().deleteObject(ann._obj)
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
def <|fim_middle|> (self):
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
g = d.getDetails().getGroup()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g._obj])
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
# make sure the group is groupwrite enabled
perms = str(d.getDetails().getGroup().getDetails().permissions)
admin.changePermissions(g._obj, omero.model.PermissionsI('rwrw--'))
d = self.getTestDataset()
g = d.getDetails().getGroup()
self.assert_(g.getDetails().permissions.isGroupWrite())
self.loginAsUser()
# User is now a member of the group to which testDataset belongs, which has groupWrite==True
# But the default group for User is diferent
try:
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
n = d.getName()
d.setName(n+'_1')
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n+'_1')
d.setName(n)
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n)
finally:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
# Revert group permissions and remove user from group
admin.changePermissions(g._obj, omero.model.PermissionsI(perms))
admin.removeGroups(omero.model.ExperimenterI(uid, False), [g._obj])
def testCrossGroupRead (self):
self.loginAsAuthor()
u = self.gateway.getUpdateService()
p = self.getTestProject()
self.assertEqual(str(p.getDetails().permissions)[4], '-')
d = p.getDetails()
g = d.getGroup()
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assert_(not g.getId() in self.gateway.getEventContext().memberOfGroups)
self.assertEqual(self.gateway.getObject('project', p.getId()), None)
def testGroupOverObjPermissions (self):
""" Object accesss must be dependent only of group permissions """
ns = 'omero.test.ns'
# Author
self.loginAsAuthor()
# create group with rw----
# create project and annotation in that group
p = dbhelpers.ProjectEntry('testAnnotationPermissions', None, create_group='testAnnotationPermissions', group_perms='rw----')
try:
p = p.create(self.gateway)
except dbhelpers.BadGroupPermissionsException:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(admin.lookupGroup('testAnnotationPermissions'), omero.model.PermissionsI('rw----'))
self.loginAsAuthor()
p = p.create(self.gateway)
pid = p.getId()
g = p.getDetails().getGroup()._obj
try:
# Admin
# add User to group
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g])
# User
# try to read project and annotation, which fails
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertEqual(self.gateway.getObject('project', pid), None)
# Admin
# Chmod project to rwrw--
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(g, omero.model.PermissionsI('rwrw--'))
# Author
# check project has proper permissions
self.loginAsAuthor()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
pa = self.gateway.getObject('project', pid)
self.assertNotEqual(pa, None)
# User
# read project and annotation
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertNotEqual(self.gateway.getObject('project', pid), None)
finally:
self.loginAsAuthor()
handle = self.gateway.deleteObjects('Project', [p.getId()], deleteAnns=True, deleteChildren=True)
self.waitOnCmd(self.gateway.c, handle)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | testCrossGroupSave |
<|file_name|>user.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
gateway tests - Users
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import unittest
import omero
import gatewaytest.library as lib
from omero.gateway.scripts import dbhelpers
class UserTest (lib.GTest):
def testUsers (self):
self.loginAsUser()
# Try reconnecting without disconnect
self._has_connected = False
self.doConnect()
self.loginAsAuthor()
self.loginAsAdmin()
def testSaveAs (self):
for u in (self.AUTHOR, self.ADMIN):
# Test image should be owned by author
self.loginAsAuthor()
image = self.getTestImage()
ownername = image.getOwnerOmeName()
# Now login as author or admin
self.doLogin(u)
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
image = self.getTestImage()
self.assertEqual(ownername, self.AUTHOR.name)
# Create some object
param = omero.sys.Parameters()
param.map = {'ns': omero.rtypes.rstring('weblitz.UserTest.testSaveAs')}
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
self.gateway.SERVICE_OPTS.setOmeroGroup()
ann = omero.gateway.CommentAnnotationWrapper(conn=self.gateway)
ann.setNs(param.map['ns'].val)
ann.setValue('foo')
ann.saveAs(image.getDetails())
# Annotations are owned by author
self.loginAsAuthor()
try:
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 1)
self.assertEqual(omero.gateway.CommentAnnotationWrapper(self.gateway, anns[0]).getOwnerOmeName(), self.AUTHOR.name)
finally:
self.gateway.getUpdateService().deleteObject(ann._obj)
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
def testCrossGroupSave (self):
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
g = d.getDetails().getGroup()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g._obj])
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
# make sure the group is groupwrite enabled
perms = str(d.getDetails().getGroup().getDetails().permissions)
admin.changePermissions(g._obj, omero.model.PermissionsI('rwrw--'))
d = self.getTestDataset()
g = d.getDetails().getGroup()
self.assert_(g.getDetails().permissions.isGroupWrite())
self.loginAsUser()
# User is now a member of the group to which testDataset belongs, which has groupWrite==True
# But the default group for User is diferent
try:
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
n = d.getName()
d.setName(n+'_1')
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n+'_1')
d.setName(n)
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n)
finally:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
# Revert group permissions and remove user from group
admin.changePermissions(g._obj, omero.model.PermissionsI(perms))
admin.removeGroups(omero.model.ExperimenterI(uid, False), [g._obj])
def <|fim_middle|> (self):
self.loginAsAuthor()
u = self.gateway.getUpdateService()
p = self.getTestProject()
self.assertEqual(str(p.getDetails().permissions)[4], '-')
d = p.getDetails()
g = d.getGroup()
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assert_(not g.getId() in self.gateway.getEventContext().memberOfGroups)
self.assertEqual(self.gateway.getObject('project', p.getId()), None)
def testGroupOverObjPermissions (self):
""" Object accesss must be dependent only of group permissions """
ns = 'omero.test.ns'
# Author
self.loginAsAuthor()
# create group with rw----
# create project and annotation in that group
p = dbhelpers.ProjectEntry('testAnnotationPermissions', None, create_group='testAnnotationPermissions', group_perms='rw----')
try:
p = p.create(self.gateway)
except dbhelpers.BadGroupPermissionsException:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(admin.lookupGroup('testAnnotationPermissions'), omero.model.PermissionsI('rw----'))
self.loginAsAuthor()
p = p.create(self.gateway)
pid = p.getId()
g = p.getDetails().getGroup()._obj
try:
# Admin
# add User to group
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g])
# User
# try to read project and annotation, which fails
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertEqual(self.gateway.getObject('project', pid), None)
# Admin
# Chmod project to rwrw--
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(g, omero.model.PermissionsI('rwrw--'))
# Author
# check project has proper permissions
self.loginAsAuthor()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
pa = self.gateway.getObject('project', pid)
self.assertNotEqual(pa, None)
# User
# read project and annotation
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertNotEqual(self.gateway.getObject('project', pid), None)
finally:
self.loginAsAuthor()
handle = self.gateway.deleteObjects('Project', [p.getId()], deleteAnns=True, deleteChildren=True)
self.waitOnCmd(self.gateway.c, handle)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | testCrossGroupRead |
<|file_name|>user.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
gateway tests - Users
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import unittest
import omero
import gatewaytest.library as lib
from omero.gateway.scripts import dbhelpers
class UserTest (lib.GTest):
def testUsers (self):
self.loginAsUser()
# Try reconnecting without disconnect
self._has_connected = False
self.doConnect()
self.loginAsAuthor()
self.loginAsAdmin()
def testSaveAs (self):
for u in (self.AUTHOR, self.ADMIN):
# Test image should be owned by author
self.loginAsAuthor()
image = self.getTestImage()
ownername = image.getOwnerOmeName()
# Now login as author or admin
self.doLogin(u)
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
image = self.getTestImage()
self.assertEqual(ownername, self.AUTHOR.name)
# Create some object
param = omero.sys.Parameters()
param.map = {'ns': omero.rtypes.rstring('weblitz.UserTest.testSaveAs')}
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
self.gateway.SERVICE_OPTS.setOmeroGroup()
ann = omero.gateway.CommentAnnotationWrapper(conn=self.gateway)
ann.setNs(param.map['ns'].val)
ann.setValue('foo')
ann.saveAs(image.getDetails())
# Annotations are owned by author
self.loginAsAuthor()
try:
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 1)
self.assertEqual(omero.gateway.CommentAnnotationWrapper(self.gateway, anns[0]).getOwnerOmeName(), self.AUTHOR.name)
finally:
self.gateway.getUpdateService().deleteObject(ann._obj)
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
def testCrossGroupSave (self):
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
g = d.getDetails().getGroup()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g._obj])
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
# make sure the group is groupwrite enabled
perms = str(d.getDetails().getGroup().getDetails().permissions)
admin.changePermissions(g._obj, omero.model.PermissionsI('rwrw--'))
d = self.getTestDataset()
g = d.getDetails().getGroup()
self.assert_(g.getDetails().permissions.isGroupWrite())
self.loginAsUser()
# User is now a member of the group to which testDataset belongs, which has groupWrite==True
# But the default group for User is diferent
try:
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
n = d.getName()
d.setName(n+'_1')
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n+'_1')
d.setName(n)
d.save()
d = self.gateway.getObject('dataset', did)
self.assertEqual(d.getName(), n)
finally:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
# Revert group permissions and remove user from group
admin.changePermissions(g._obj, omero.model.PermissionsI(perms))
admin.removeGroups(omero.model.ExperimenterI(uid, False), [g._obj])
def testCrossGroupRead (self):
self.loginAsAuthor()
u = self.gateway.getUpdateService()
p = self.getTestProject()
self.assertEqual(str(p.getDetails().permissions)[4], '-')
d = p.getDetails()
g = d.getGroup()
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assert_(not g.getId() in self.gateway.getEventContext().memberOfGroups)
self.assertEqual(self.gateway.getObject('project', p.getId()), None)
def <|fim_middle|> (self):
""" Object accesss must be dependent only of group permissions """
ns = 'omero.test.ns'
# Author
self.loginAsAuthor()
# create group with rw----
# create project and annotation in that group
p = dbhelpers.ProjectEntry('testAnnotationPermissions', None, create_group='testAnnotationPermissions', group_perms='rw----')
try:
p = p.create(self.gateway)
except dbhelpers.BadGroupPermissionsException:
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(admin.lookupGroup('testAnnotationPermissions'), omero.model.PermissionsI('rw----'))
self.loginAsAuthor()
p = p.create(self.gateway)
pid = p.getId()
g = p.getDetails().getGroup()._obj
try:
# Admin
# add User to group
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.addGroups(omero.model.ExperimenterI(uid, False), [g])
# User
# try to read project and annotation, which fails
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertEqual(self.gateway.getObject('project', pid), None)
# Admin
# Chmod project to rwrw--
self.loginAsAdmin()
admin = self.gateway.getAdminService()
admin.changePermissions(g, omero.model.PermissionsI('rwrw--'))
# Author
# check project has proper permissions
self.loginAsAuthor()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
pa = self.gateway.getObject('project', pid)
self.assertNotEqual(pa, None)
# User
# read project and annotation
self.loginAsUser()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
self.assertNotEqual(self.gateway.getObject('project', pid), None)
finally:
self.loginAsAuthor()
handle = self.gateway.deleteObjects('Project', [p.getId()], deleteAnns=True, deleteChildren=True)
self.waitOnCmd(self.gateway.c, handle)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | testGroupOverObjPermissions |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, division, print_function, unicode_literals
import string
import urllib
try:
from urllib.parse import urlparse, urlencode, urljoin, parse_qsl, urlunparse
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urlparse import urlparse, urljoin, urlunparse, parse_qsl
from urllib import urlencode
from urllib2 import urlopen, Request, HTTPError
from random import SystemRandom
try:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters +
string.digits)
except AttributeError:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters.decode('ascii') +
string.digits.decode('ascii'))
def random_ascii_string(length):
random = SystemRandom()
return ''.join([random.choice(UNICODE_ASCII_CHARACTERS) for x in range(length)])
def url_query_params(url):
"""Return query parameters as a dict from the specified URL.
:param url: URL.
:type url: str
:rtype: dict
"""
return dict(parse_qsl(urlparse(url).query, True))
def url_dequery(url):
"""Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urlparse(url)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
'',
url.fragment))
def build_url(base, additional_params=None):
"""Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: Additional query parameters to include.
:type additional_params: dict
:rtype: str
"""
url = urlparse(base)
query_params = {}<|fim▁hole|> if v is None:
query_params.pop(k)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
urlencode(query_params),
url.fragment))<|fim▁end|> | query_params.update(parse_qsl(url.query, True))
if additional_params is not None:
query_params.update(additional_params)
for k, v in additional_params.items(): |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, division, print_function, unicode_literals
import string
import urllib
try:
from urllib.parse import urlparse, urlencode, urljoin, parse_qsl, urlunparse
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urlparse import urlparse, urljoin, urlunparse, parse_qsl
from urllib import urlencode
from urllib2 import urlopen, Request, HTTPError
from random import SystemRandom
try:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters +
string.digits)
except AttributeError:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters.decode('ascii') +
string.digits.decode('ascii'))
def random_ascii_string(length):
<|fim_middle|>
def url_query_params(url):
"""Return query parameters as a dict from the specified URL.
:param url: URL.
:type url: str
:rtype: dict
"""
return dict(parse_qsl(urlparse(url).query, True))
def url_dequery(url):
"""Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urlparse(url)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
'',
url.fragment))
def build_url(base, additional_params=None):
"""Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: Additional query parameters to include.
:type additional_params: dict
:rtype: str
"""
url = urlparse(base)
query_params = {}
query_params.update(parse_qsl(url.query, True))
if additional_params is not None:
query_params.update(additional_params)
for k, v in additional_params.items():
if v is None:
query_params.pop(k)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
urlencode(query_params),
url.fragment))
<|fim▁end|> | random = SystemRandom()
return ''.join([random.choice(UNICODE_ASCII_CHARACTERS) for x in range(length)]) |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, division, print_function, unicode_literals
import string
import urllib
try:
from urllib.parse import urlparse, urlencode, urljoin, parse_qsl, urlunparse
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urlparse import urlparse, urljoin, urlunparse, parse_qsl
from urllib import urlencode
from urllib2 import urlopen, Request, HTTPError
from random import SystemRandom
try:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters +
string.digits)
except AttributeError:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters.decode('ascii') +
string.digits.decode('ascii'))
def random_ascii_string(length):
random = SystemRandom()
return ''.join([random.choice(UNICODE_ASCII_CHARACTERS) for x in range(length)])
def url_query_params(url):
<|fim_middle|>
def url_dequery(url):
"""Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urlparse(url)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
'',
url.fragment))
def build_url(base, additional_params=None):
"""Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: Additional query parameters to include.
:type additional_params: dict
:rtype: str
"""
url = urlparse(base)
query_params = {}
query_params.update(parse_qsl(url.query, True))
if additional_params is not None:
query_params.update(additional_params)
for k, v in additional_params.items():
if v is None:
query_params.pop(k)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
urlencode(query_params),
url.fragment))
<|fim▁end|> | """Return query parameters as a dict from the specified URL.
:param url: URL.
:type url: str
:rtype: dict
"""
return dict(parse_qsl(urlparse(url).query, True)) |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, division, print_function, unicode_literals
import string
import urllib
try:
from urllib.parse import urlparse, urlencode, urljoin, parse_qsl, urlunparse
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urlparse import urlparse, urljoin, urlunparse, parse_qsl
from urllib import urlencode
from urllib2 import urlopen, Request, HTTPError
from random import SystemRandom
try:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters +
string.digits)
except AttributeError:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters.decode('ascii') +
string.digits.decode('ascii'))
def random_ascii_string(length):
random = SystemRandom()
return ''.join([random.choice(UNICODE_ASCII_CHARACTERS) for x in range(length)])
def url_query_params(url):
"""Return query parameters as a dict from the specified URL.
:param url: URL.
:type url: str
:rtype: dict
"""
return dict(parse_qsl(urlparse(url).query, True))
def url_dequery(url):
<|fim_middle|>
def build_url(base, additional_params=None):
"""Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: Additional query parameters to include.
:type additional_params: dict
:rtype: str
"""
url = urlparse(base)
query_params = {}
query_params.update(parse_qsl(url.query, True))
if additional_params is not None:
query_params.update(additional_params)
for k, v in additional_params.items():
if v is None:
query_params.pop(k)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
urlencode(query_params),
url.fragment))
<|fim▁end|> | """Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urlparse(url)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
'',
url.fragment)) |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, division, print_function, unicode_literals
import string
import urllib
try:
from urllib.parse import urlparse, urlencode, urljoin, parse_qsl, urlunparse
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urlparse import urlparse, urljoin, urlunparse, parse_qsl
from urllib import urlencode
from urllib2 import urlopen, Request, HTTPError
from random import SystemRandom
try:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters +
string.digits)
except AttributeError:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters.decode('ascii') +
string.digits.decode('ascii'))
def random_ascii_string(length):
random = SystemRandom()
return ''.join([random.choice(UNICODE_ASCII_CHARACTERS) for x in range(length)])
def url_query_params(url):
"""Return query parameters as a dict from the specified URL.
:param url: URL.
:type url: str
:rtype: dict
"""
return dict(parse_qsl(urlparse(url).query, True))
def url_dequery(url):
"""Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urlparse(url)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
'',
url.fragment))
def build_url(base, additional_params=None):
<|fim_middle|>
<|fim▁end|> | """Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: Additional query parameters to include.
:type additional_params: dict
:rtype: str
"""
url = urlparse(base)
query_params = {}
query_params.update(parse_qsl(url.query, True))
if additional_params is not None:
query_params.update(additional_params)
for k, v in additional_params.items():
if v is None:
query_params.pop(k)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
urlencode(query_params),
url.fragment)) |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, division, print_function, unicode_literals
import string
import urllib
try:
from urllib.parse import urlparse, urlencode, urljoin, parse_qsl, urlunparse
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urlparse import urlparse, urljoin, urlunparse, parse_qsl
from urllib import urlencode
from urllib2 import urlopen, Request, HTTPError
from random import SystemRandom
try:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters +
string.digits)
except AttributeError:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters.decode('ascii') +
string.digits.decode('ascii'))
def random_ascii_string(length):
random = SystemRandom()
return ''.join([random.choice(UNICODE_ASCII_CHARACTERS) for x in range(length)])
def url_query_params(url):
"""Return query parameters as a dict from the specified URL.
:param url: URL.
:type url: str
:rtype: dict
"""
return dict(parse_qsl(urlparse(url).query, True))
def url_dequery(url):
"""Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urlparse(url)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
'',
url.fragment))
def build_url(base, additional_params=None):
"""Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: Additional query parameters to include.
:type additional_params: dict
:rtype: str
"""
url = urlparse(base)
query_params = {}
query_params.update(parse_qsl(url.query, True))
if additional_params is not None:
<|fim_middle|>
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
urlencode(query_params),
url.fragment))
<|fim▁end|> | query_params.update(additional_params)
for k, v in additional_params.items():
if v is None:
query_params.pop(k) |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, division, print_function, unicode_literals
import string
import urllib
try:
from urllib.parse import urlparse, urlencode, urljoin, parse_qsl, urlunparse
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urlparse import urlparse, urljoin, urlunparse, parse_qsl
from urllib import urlencode
from urllib2 import urlopen, Request, HTTPError
from random import SystemRandom
try:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters +
string.digits)
except AttributeError:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters.decode('ascii') +
string.digits.decode('ascii'))
def random_ascii_string(length):
random = SystemRandom()
return ''.join([random.choice(UNICODE_ASCII_CHARACTERS) for x in range(length)])
def url_query_params(url):
"""Return query parameters as a dict from the specified URL.
:param url: URL.
:type url: str
:rtype: dict
"""
return dict(parse_qsl(urlparse(url).query, True))
def url_dequery(url):
"""Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urlparse(url)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
'',
url.fragment))
def build_url(base, additional_params=None):
"""Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: Additional query parameters to include.
:type additional_params: dict
:rtype: str
"""
url = urlparse(base)
query_params = {}
query_params.update(parse_qsl(url.query, True))
if additional_params is not None:
query_params.update(additional_params)
for k, v in additional_params.items():
if v is None:
<|fim_middle|>
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
urlencode(query_params),
url.fragment))
<|fim▁end|> | query_params.pop(k) |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, division, print_function, unicode_literals
import string
import urllib
try:
from urllib.parse import urlparse, urlencode, urljoin, parse_qsl, urlunparse
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urlparse import urlparse, urljoin, urlunparse, parse_qsl
from urllib import urlencode
from urllib2 import urlopen, Request, HTTPError
from random import SystemRandom
try:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters +
string.digits)
except AttributeError:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters.decode('ascii') +
string.digits.decode('ascii'))
def <|fim_middle|>(length):
random = SystemRandom()
return ''.join([random.choice(UNICODE_ASCII_CHARACTERS) for x in range(length)])
def url_query_params(url):
"""Return query parameters as a dict from the specified URL.
:param url: URL.
:type url: str
:rtype: dict
"""
return dict(parse_qsl(urlparse(url).query, True))
def url_dequery(url):
"""Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urlparse(url)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
'',
url.fragment))
def build_url(base, additional_params=None):
"""Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: Additional query parameters to include.
:type additional_params: dict
:rtype: str
"""
url = urlparse(base)
query_params = {}
query_params.update(parse_qsl(url.query, True))
if additional_params is not None:
query_params.update(additional_params)
for k, v in additional_params.items():
if v is None:
query_params.pop(k)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
urlencode(query_params),
url.fragment))
<|fim▁end|> | random_ascii_string |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, division, print_function, unicode_literals
import string
import urllib
try:
from urllib.parse import urlparse, urlencode, urljoin, parse_qsl, urlunparse
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urlparse import urlparse, urljoin, urlunparse, parse_qsl
from urllib import urlencode
from urllib2 import urlopen, Request, HTTPError
from random import SystemRandom
try:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters +
string.digits)
except AttributeError:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters.decode('ascii') +
string.digits.decode('ascii'))
def random_ascii_string(length):
random = SystemRandom()
return ''.join([random.choice(UNICODE_ASCII_CHARACTERS) for x in range(length)])
def <|fim_middle|>(url):
"""Return query parameters as a dict from the specified URL.
:param url: URL.
:type url: str
:rtype: dict
"""
return dict(parse_qsl(urlparse(url).query, True))
def url_dequery(url):
"""Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urlparse(url)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
'',
url.fragment))
def build_url(base, additional_params=None):
"""Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: Additional query parameters to include.
:type additional_params: dict
:rtype: str
"""
url = urlparse(base)
query_params = {}
query_params.update(parse_qsl(url.query, True))
if additional_params is not None:
query_params.update(additional_params)
for k, v in additional_params.items():
if v is None:
query_params.pop(k)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
urlencode(query_params),
url.fragment))
<|fim▁end|> | url_query_params |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, division, print_function, unicode_literals
import string
import urllib
try:
from urllib.parse import urlparse, urlencode, urljoin, parse_qsl, urlunparse
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urlparse import urlparse, urljoin, urlunparse, parse_qsl
from urllib import urlencode
from urllib2 import urlopen, Request, HTTPError
from random import SystemRandom
try:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters +
string.digits)
except AttributeError:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters.decode('ascii') +
string.digits.decode('ascii'))
def random_ascii_string(length):
random = SystemRandom()
return ''.join([random.choice(UNICODE_ASCII_CHARACTERS) for x in range(length)])
def url_query_params(url):
"""Return query parameters as a dict from the specified URL.
:param url: URL.
:type url: str
:rtype: dict
"""
return dict(parse_qsl(urlparse(url).query, True))
def <|fim_middle|>(url):
"""Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urlparse(url)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
'',
url.fragment))
def build_url(base, additional_params=None):
"""Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: Additional query parameters to include.
:type additional_params: dict
:rtype: str
"""
url = urlparse(base)
query_params = {}
query_params.update(parse_qsl(url.query, True))
if additional_params is not None:
query_params.update(additional_params)
for k, v in additional_params.items():
if v is None:
query_params.pop(k)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
urlencode(query_params),
url.fragment))
<|fim▁end|> | url_dequery |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, division, print_function, unicode_literals
import string
import urllib
try:
from urllib.parse import urlparse, urlencode, urljoin, parse_qsl, urlunparse
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urlparse import urlparse, urljoin, urlunparse, parse_qsl
from urllib import urlencode
from urllib2 import urlopen, Request, HTTPError
from random import SystemRandom
try:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters +
string.digits)
except AttributeError:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters.decode('ascii') +
string.digits.decode('ascii'))
def random_ascii_string(length):
random = SystemRandom()
return ''.join([random.choice(UNICODE_ASCII_CHARACTERS) for x in range(length)])
def url_query_params(url):
"""Return query parameters as a dict from the specified URL.
:param url: URL.
:type url: str
:rtype: dict
"""
return dict(parse_qsl(urlparse(url).query, True))
def url_dequery(url):
"""Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urlparse(url)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
'',
url.fragment))
def <|fim_middle|>(base, additional_params=None):
"""Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: Additional query parameters to include.
:type additional_params: dict
:rtype: str
"""
url = urlparse(base)
query_params = {}
query_params.update(parse_qsl(url.query, True))
if additional_params is not None:
query_params.update(additional_params)
for k, v in additional_params.items():
if v is None:
query_params.pop(k)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
urlencode(query_params),
url.fragment))
<|fim▁end|> | build_url |
<|file_name|>g3c.py<|end_file_name|><|fim▁begin|>from . import Cl, conformalize<|fim▁hole|>layout, blades, stuff = conformalize(layout_orig)
locals().update(blades)
locals().update(stuff)
# for shorter reprs
layout.__name__ = 'layout'
layout.__module__ = __name__<|fim▁end|> | layout_orig, blades_orig = Cl(3) |
<|file_name|>media.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
eve.io.media
~~~~~~~~~~~~
Media storage for Eve-powered APIs.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
class MediaStorage(object):
""" The MediaStorage class provides a standardized API for storing files,
along with a set of default behaviors that all other storage systems can
inherit or override as necessary.
..versioneadded:: 0.3
"""
def __init__(self, app=None):
"""
:param app: the flask application (eve itself). This can be used by
the class to access, amongst other things, the app.config object to
retrieve class-specific settings.
"""
self.app = app
def get(self, id_or_filename):
""" Opens the file given by name or unique id. Note that although the
returned file is guaranteed to be a File object, it might actually be
some subclass. Returns None if no file was found.
"""
raise NotImplementedError
def put(self, content, filename=None, content_type=None):
""" Saves a new file using the storage system, preferably with the name
specified. If there already exists a file with this name name, the
storage system may modify the filename as necessary to get a unique
name. Depending on the storage system, a unique id or the actual name
of the stored file will be returned. The content type argument is used
to appropriately identify the file when it is retrieved.
.. versionchanged:: 0.5
Allow filename to be optional (#414).
"""
raise NotImplementedError
<|fim▁hole|> """
raise NotImplementedError
def exists(self, id_or_filename):
""" Returns True if a file referenced by the given name or unique id
already exists in the storage system, or False if the name is available
for a new file.
"""
raise NotImplementedError<|fim▁end|> | def delete(self, id_or_filename):
""" Deletes the file referenced by name or unique id. If deletion is
not supported on the target storage system this will raise
NotImplementedError instead |
<|file_name|>media.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
eve.io.media
~~~~~~~~~~~~
Media storage for Eve-powered APIs.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
class MediaStorage(object):
<|fim_middle|>
<|fim▁end|> | """ The MediaStorage class provides a standardized API for storing files,
along with a set of default behaviors that all other storage systems can
inherit or override as necessary.
..versioneadded:: 0.3
"""
def __init__(self, app=None):
"""
:param app: the flask application (eve itself). This can be used by
the class to access, amongst other things, the app.config object to
retrieve class-specific settings.
"""
self.app = app
def get(self, id_or_filename):
""" Opens the file given by name or unique id. Note that although the
returned file is guaranteed to be a File object, it might actually be
some subclass. Returns None if no file was found.
"""
raise NotImplementedError
def put(self, content, filename=None, content_type=None):
""" Saves a new file using the storage system, preferably with the name
specified. If there already exists a file with this name name, the
storage system may modify the filename as necessary to get a unique
name. Depending on the storage system, a unique id or the actual name
of the stored file will be returned. The content type argument is used
to appropriately identify the file when it is retrieved.
.. versionchanged:: 0.5
Allow filename to be optional (#414).
"""
raise NotImplementedError
def delete(self, id_or_filename):
""" Deletes the file referenced by name or unique id. If deletion is
not supported on the target storage system this will raise
NotImplementedError instead
"""
raise NotImplementedError
def exists(self, id_or_filename):
""" Returns True if a file referenced by the given name or unique id
already exists in the storage system, or False if the name is available
for a new file.
"""
raise NotImplementedError |
<|file_name|>media.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
eve.io.media
~~~~~~~~~~~~
Media storage for Eve-powered APIs.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
class MediaStorage(object):
""" The MediaStorage class provides a standardized API for storing files,
along with a set of default behaviors that all other storage systems can
inherit or override as necessary.
..versioneadded:: 0.3
"""
def __init__(self, app=None):
<|fim_middle|>
def get(self, id_or_filename):
""" Opens the file given by name or unique id. Note that although the
returned file is guaranteed to be a File object, it might actually be
some subclass. Returns None if no file was found.
"""
raise NotImplementedError
def put(self, content, filename=None, content_type=None):
""" Saves a new file using the storage system, preferably with the name
specified. If there already exists a file with this name name, the
storage system may modify the filename as necessary to get a unique
name. Depending on the storage system, a unique id or the actual name
of the stored file will be returned. The content type argument is used
to appropriately identify the file when it is retrieved.
.. versionchanged:: 0.5
Allow filename to be optional (#414).
"""
raise NotImplementedError
def delete(self, id_or_filename):
""" Deletes the file referenced by name or unique id. If deletion is
not supported on the target storage system this will raise
NotImplementedError instead
"""
raise NotImplementedError
def exists(self, id_or_filename):
""" Returns True if a file referenced by the given name or unique id
already exists in the storage system, or False if the name is available
for a new file.
"""
raise NotImplementedError
<|fim▁end|> | """
:param app: the flask application (eve itself). This can be used by
the class to access, amongst other things, the app.config object to
retrieve class-specific settings.
"""
self.app = app |
<|file_name|>media.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
eve.io.media
~~~~~~~~~~~~
Media storage for Eve-powered APIs.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
class MediaStorage(object):
""" The MediaStorage class provides a standardized API for storing files,
along with a set of default behaviors that all other storage systems can
inherit or override as necessary.
..versioneadded:: 0.3
"""
def __init__(self, app=None):
"""
:param app: the flask application (eve itself). This can be used by
the class to access, amongst other things, the app.config object to
retrieve class-specific settings.
"""
self.app = app
def get(self, id_or_filename):
<|fim_middle|>
def put(self, content, filename=None, content_type=None):
""" Saves a new file using the storage system, preferably with the name
specified. If there already exists a file with this name name, the
storage system may modify the filename as necessary to get a unique
name. Depending on the storage system, a unique id or the actual name
of the stored file will be returned. The content type argument is used
to appropriately identify the file when it is retrieved.
.. versionchanged:: 0.5
Allow filename to be optional (#414).
"""
raise NotImplementedError
def delete(self, id_or_filename):
""" Deletes the file referenced by name or unique id. If deletion is
not supported on the target storage system this will raise
NotImplementedError instead
"""
raise NotImplementedError
def exists(self, id_or_filename):
""" Returns True if a file referenced by the given name or unique id
already exists in the storage system, or False if the name is available
for a new file.
"""
raise NotImplementedError
<|fim▁end|> | """ Opens the file given by name or unique id. Note that although the
returned file is guaranteed to be a File object, it might actually be
some subclass. Returns None if no file was found.
"""
raise NotImplementedError |
<|file_name|>media.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
eve.io.media
~~~~~~~~~~~~
Media storage for Eve-powered APIs.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
class MediaStorage(object):
""" The MediaStorage class provides a standardized API for storing files,
along with a set of default behaviors that all other storage systems can
inherit or override as necessary.
..versioneadded:: 0.3
"""
def __init__(self, app=None):
"""
:param app: the flask application (eve itself). This can be used by
the class to access, amongst other things, the app.config object to
retrieve class-specific settings.
"""
self.app = app
def get(self, id_or_filename):
""" Opens the file given by name or unique id. Note that although the
returned file is guaranteed to be a File object, it might actually be
some subclass. Returns None if no file was found.
"""
raise NotImplementedError
def put(self, content, filename=None, content_type=None):
<|fim_middle|>
def delete(self, id_or_filename):
""" Deletes the file referenced by name or unique id. If deletion is
not supported on the target storage system this will raise
NotImplementedError instead
"""
raise NotImplementedError
def exists(self, id_or_filename):
""" Returns True if a file referenced by the given name or unique id
already exists in the storage system, or False if the name is available
for a new file.
"""
raise NotImplementedError
<|fim▁end|> | """ Saves a new file using the storage system, preferably with the name
specified. If there already exists a file with this name name, the
storage system may modify the filename as necessary to get a unique
name. Depending on the storage system, a unique id or the actual name
of the stored file will be returned. The content type argument is used
to appropriately identify the file when it is retrieved.
.. versionchanged:: 0.5
Allow filename to be optional (#414).
"""
raise NotImplementedError |
<|file_name|>media.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
eve.io.media
~~~~~~~~~~~~
Media storage for Eve-powered APIs.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
class MediaStorage(object):
""" The MediaStorage class provides a standardized API for storing files,
along with a set of default behaviors that all other storage systems can
inherit or override as necessary.
..versioneadded:: 0.3
"""
def __init__(self, app=None):
"""
:param app: the flask application (eve itself). This can be used by
the class to access, amongst other things, the app.config object to
retrieve class-specific settings.
"""
self.app = app
def get(self, id_or_filename):
""" Opens the file given by name or unique id. Note that although the
returned file is guaranteed to be a File object, it might actually be
some subclass. Returns None if no file was found.
"""
raise NotImplementedError
def put(self, content, filename=None, content_type=None):
""" Saves a new file using the storage system, preferably with the name
specified. If there already exists a file with this name name, the
storage system may modify the filename as necessary to get a unique
name. Depending on the storage system, a unique id or the actual name
of the stored file will be returned. The content type argument is used
to appropriately identify the file when it is retrieved.
.. versionchanged:: 0.5
Allow filename to be optional (#414).
"""
raise NotImplementedError
def delete(self, id_or_filename):
<|fim_middle|>
def exists(self, id_or_filename):
""" Returns True if a file referenced by the given name or unique id
already exists in the storage system, or False if the name is available
for a new file.
"""
raise NotImplementedError
<|fim▁end|> | """ Deletes the file referenced by name or unique id. If deletion is
not supported on the target storage system this will raise
NotImplementedError instead
"""
raise NotImplementedError |
<|file_name|>media.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
eve.io.media
~~~~~~~~~~~~
Media storage for Eve-powered APIs.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
class MediaStorage(object):
""" The MediaStorage class provides a standardized API for storing files,
along with a set of default behaviors that all other storage systems can
inherit or override as necessary.
..versioneadded:: 0.3
"""
def __init__(self, app=None):
"""
:param app: the flask application (eve itself). This can be used by
the class to access, amongst other things, the app.config object to
retrieve class-specific settings.
"""
self.app = app
def get(self, id_or_filename):
""" Opens the file given by name or unique id. Note that although the
returned file is guaranteed to be a File object, it might actually be
some subclass. Returns None if no file was found.
"""
raise NotImplementedError
def put(self, content, filename=None, content_type=None):
""" Saves a new file using the storage system, preferably with the name
specified. If there already exists a file with this name name, the
storage system may modify the filename as necessary to get a unique
name. Depending on the storage system, a unique id or the actual name
of the stored file will be returned. The content type argument is used
to appropriately identify the file when it is retrieved.
.. versionchanged:: 0.5
Allow filename to be optional (#414).
"""
raise NotImplementedError
def delete(self, id_or_filename):
""" Deletes the file referenced by name or unique id. If deletion is
not supported on the target storage system this will raise
NotImplementedError instead
"""
raise NotImplementedError
def exists(self, id_or_filename):
<|fim_middle|>
<|fim▁end|> | """ Returns True if a file referenced by the given name or unique id
already exists in the storage system, or False if the name is available
for a new file.
"""
raise NotImplementedError |
<|file_name|>media.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
eve.io.media
~~~~~~~~~~~~
Media storage for Eve-powered APIs.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
class MediaStorage(object):
""" The MediaStorage class provides a standardized API for storing files,
along with a set of default behaviors that all other storage systems can
inherit or override as necessary.
..versioneadded:: 0.3
"""
def <|fim_middle|>(self, app=None):
"""
:param app: the flask application (eve itself). This can be used by
the class to access, amongst other things, the app.config object to
retrieve class-specific settings.
"""
self.app = app
def get(self, id_or_filename):
""" Opens the file given by name or unique id. Note that although the
returned file is guaranteed to be a File object, it might actually be
some subclass. Returns None if no file was found.
"""
raise NotImplementedError
def put(self, content, filename=None, content_type=None):
""" Saves a new file using the storage system, preferably with the name
specified. If there already exists a file with this name name, the
storage system may modify the filename as necessary to get a unique
name. Depending on the storage system, a unique id or the actual name
of the stored file will be returned. The content type argument is used
to appropriately identify the file when it is retrieved.
.. versionchanged:: 0.5
Allow filename to be optional (#414).
"""
raise NotImplementedError
def delete(self, id_or_filename):
""" Deletes the file referenced by name or unique id. If deletion is
not supported on the target storage system this will raise
NotImplementedError instead
"""
raise NotImplementedError
def exists(self, id_or_filename):
""" Returns True if a file referenced by the given name or unique id
already exists in the storage system, or False if the name is available
for a new file.
"""
raise NotImplementedError
<|fim▁end|> | __init__ |
<|file_name|>media.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
eve.io.media
~~~~~~~~~~~~
Media storage for Eve-powered APIs.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
class MediaStorage(object):
""" The MediaStorage class provides a standardized API for storing files,
along with a set of default behaviors that all other storage systems can
inherit or override as necessary.
..versioneadded:: 0.3
"""
def __init__(self, app=None):
"""
:param app: the flask application (eve itself). This can be used by
the class to access, amongst other things, the app.config object to
retrieve class-specific settings.
"""
self.app = app
def <|fim_middle|>(self, id_or_filename):
""" Opens the file given by name or unique id. Note that although the
returned file is guaranteed to be a File object, it might actually be
some subclass. Returns None if no file was found.
"""
raise NotImplementedError
def put(self, content, filename=None, content_type=None):
""" Saves a new file using the storage system, preferably with the name
specified. If there already exists a file with this name name, the
storage system may modify the filename as necessary to get a unique
name. Depending on the storage system, a unique id or the actual name
of the stored file will be returned. The content type argument is used
to appropriately identify the file when it is retrieved.
.. versionchanged:: 0.5
Allow filename to be optional (#414).
"""
raise NotImplementedError
def delete(self, id_or_filename):
""" Deletes the file referenced by name or unique id. If deletion is
not supported on the target storage system this will raise
NotImplementedError instead
"""
raise NotImplementedError
def exists(self, id_or_filename):
""" Returns True if a file referenced by the given name or unique id
already exists in the storage system, or False if the name is available
for a new file.
"""
raise NotImplementedError
<|fim▁end|> | get |
<|file_name|>media.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
eve.io.media
~~~~~~~~~~~~
Media storage for Eve-powered APIs.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
class MediaStorage(object):
""" The MediaStorage class provides a standardized API for storing files,
along with a set of default behaviors that all other storage systems can
inherit or override as necessary.
..versioneadded:: 0.3
"""
def __init__(self, app=None):
"""
:param app: the flask application (eve itself). This can be used by
the class to access, amongst other things, the app.config object to
retrieve class-specific settings.
"""
self.app = app
def get(self, id_or_filename):
""" Opens the file given by name or unique id. Note that although the
returned file is guaranteed to be a File object, it might actually be
some subclass. Returns None if no file was found.
"""
raise NotImplementedError
def <|fim_middle|>(self, content, filename=None, content_type=None):
""" Saves a new file using the storage system, preferably with the name
specified. If there already exists a file with this name name, the
storage system may modify the filename as necessary to get a unique
name. Depending on the storage system, a unique id or the actual name
of the stored file will be returned. The content type argument is used
to appropriately identify the file when it is retrieved.
.. versionchanged:: 0.5
Allow filename to be optional (#414).
"""
raise NotImplementedError
def delete(self, id_or_filename):
""" Deletes the file referenced by name or unique id. If deletion is
not supported on the target storage system this will raise
NotImplementedError instead
"""
raise NotImplementedError
def exists(self, id_or_filename):
""" Returns True if a file referenced by the given name or unique id
already exists in the storage system, or False if the name is available
for a new file.
"""
raise NotImplementedError
<|fim▁end|> | put |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.