idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
24,100
def vbkv_loads ( s , mapper = dict , merge_duplicate_keys = True ) : if s [ : 4 ] != b'VBKV' : raise ValueError ( "Invalid header" ) checksum , = struct . unpack ( '<i' , s [ 4 : 8 ] ) if checksum != crc32 ( s [ 8 : ] ) : raise ValueError ( "Invalid checksum" ) return binary_loads ( s [ 8 : ] , mapper , merge_duplicate_keys , alt_format = True )
Deserialize s ( bytes containing a VBKV to a Python object .
123
17
24,101
def vbkv_dumps ( obj ) : data = b'' . join ( _binary_dump_gen ( obj , alt_format = True ) ) checksum = crc32 ( data ) return b'VBKV' + struct . pack ( '<i' , checksum ) + data
Serialize obj to a VBKV formatted bytes .
66
12
24,102
def signature_validate ( signature , error = None ) : error , my_error = _get_error ( error ) result = dbus . dbus_signature_validate ( signature . encode ( ) , error . _dbobj ) != 0 my_error . raise_if_set ( ) return result
is signature a valid sequence of zero or more complete types .
67
12
24,103
def unparse_signature ( signature ) : signature = parse_signature ( signature ) if not isinstance ( signature , ( tuple , list ) ) : signature = [ signature ] #end if return DBUS . Signature ( "" . join ( t . signature for t in signature ) )
converts a signature from parsed form to string form .
60
11
24,104
def signature_validate_single ( signature , error = None ) : error , my_error = _get_error ( error ) result = dbus . dbus_signature_validate_single ( signature . encode ( ) , error . _dbobj ) != 0 my_error . raise_if_set ( ) return result
is signature a single valid type .
71
7
24,105
def split_path ( path ) : if isinstance ( path , ( tuple , list ) ) : result = path # assume already split elif path == "/" : result = [ ] else : if not path . startswith ( "/" ) or path . endswith ( "/" ) : raise DBusError ( DBUS . ERROR_INVALID_ARGS , "invalid path %s" % repr ( path ) ) #end if result = path . split ( "/" ) [ 1 : ] #end if return result
convenience routine for splitting a path into a list of components .
114
14
24,106
def validate_utf8 ( alleged_utf8 , error = None ) : error , my_error = _get_error ( error ) result = dbus . dbus_validate_utf8 ( alleged_utf8 , error . _dbobj ) != 0 my_error . raise_if_set ( ) return result
alleged_utf8 must be null - terminated bytes .
69
13
24,107
def int_subtype ( i , bits , signed ) : if not isinstance ( i , int ) : raise TypeError ( "value is not int: %s" % repr ( i ) ) #end if if signed : lo = - 1 << bits - 1 hi = ( 1 << bits - 1 ) - 1 else : lo = 0 hi = ( 1 << bits ) - 1 #end if if i < lo or i > hi : raise ValueError ( "%d not in range of %s %d-bit value" % ( i , ( "unsigned" , "signed" ) [ signed ] , bits ) ) #end if return i
returns integer i after checking that it fits in the given number of bits .
136
16
24,108
def server_id ( self ) : c_result = dbus . dbus_connection_get_server_id ( self . _dbobj ) result = ct . cast ( c_result , ct . c_char_p ) . value . decode ( ) dbus . dbus_free ( c_result ) return result
asks the server at the other end for its unique id .
72
12
24,109
def send ( self , message ) : if not isinstance ( message , Message ) : raise TypeError ( "message must be a Message" ) #end if serial = ct . c_uint ( ) if not dbus . dbus_connection_send ( self . _dbobj , message . _dbobj , ct . byref ( serial ) ) : raise CallFailed ( "dbus_connection_send" ) #end if return serial . value
puts a message in the outgoing queue .
98
9
24,110
def send_with_reply_and_block ( self , message , timeout = DBUS . TIMEOUT_USE_DEFAULT , error = None ) : if not isinstance ( message , Message ) : raise TypeError ( "message must be a Message" ) #end if error , my_error = _get_error ( error ) reply = dbus . dbus_connection_send_with_reply_and_block ( self . _dbobj , message . _dbobj , _get_timeout ( timeout ) , error . _dbobj ) my_error . raise_if_set ( ) if reply != None : result = Message ( reply ) else : result = None #end if return result
sends a message blocks the thread until the reply is available and returns it .
149
16
24,111
def list_registered ( self , parent_path ) : child_entries = ct . POINTER ( ct . c_char_p ) ( ) if not dbus . dbus_connection_list_registered ( self . _dbobj , parent_path . encode ( ) , ct . byref ( child_entries ) ) : raise CallFailed ( "dbus_connection_list_registered" ) #end if result = [ ] i = 0 while True : entry = child_entries [ i ] if entry == None : break result . append ( entry . decode ( ) ) i += 1 #end while dbus . dbus_free_string_array ( child_entries ) return result
lists all the object paths for which you have ObjectPathVTable handlers registered .
154
16
24,112
def bus_get ( celf , type , private , error = None ) : error , my_error = _get_error ( error ) result = ( dbus . dbus_bus_get , dbus . dbus_bus_get_private ) [ private ] ( type , error . _dbobj ) my_error . raise_if_set ( ) if result != None : result = celf ( result ) #end if return result
returns a Connection to one of the predefined D - Bus buses ; type is a BUS_xxx value .
95
23
24,113
def become_monitor ( self , rules ) : message = Message . new_method_call ( destination = DBUS . SERVICE_DBUS , path = DBUS . PATH_DBUS , iface = DBUS . INTERFACE_MONITORING , method = "BecomeMonitor" ) message . append_objects ( "asu" , ( list ( format_rule ( rule ) for rule in rules ) ) , 0 ) self . send ( message )
turns the connection into one that can only receive monitoring messages .
96
13
24,114
def send ( self , message ) : if not isinstance ( message , Message ) : raise TypeError ( "message must be a Message" ) #end if assert not self . _sent , "preallocated has already been sent" serial = ct . c_uint ( ) dbus . dbus_connection_send_preallocated ( self . _parent . _dbobj , self . _dbobj , message . _dbobj , ct . byref ( serial ) ) self . _sent = True return serial . value
alternative to Connection . send_preallocated .
113
11
24,115
def new_error ( self , name , message ) : result = dbus . dbus_message_new_error ( self . _dbobj , name . encode ( ) , ( lambda : None , lambda : message . encode ( ) ) [ message != None ] ( ) ) if result == None : raise CallFailed ( "dbus_message_new_error" ) #end if return type ( self ) ( result )
creates a new DBUS . MESSAGE_TYPE_ERROR message that is a reply to this Message .
91
24
24,116
def new_method_call ( celf , destination , path , iface , method ) : result = dbus . dbus_message_new_method_call ( ( lambda : None , lambda : destination . encode ( ) ) [ destination != None ] ( ) , path . encode ( ) , ( lambda : None , lambda : iface . encode ( ) ) [ iface != None ] ( ) , method . encode ( ) , ) if result == None : raise CallFailed ( "dbus_message_new_method_call" ) #end if return celf ( result )
creates a new DBUS . MESSAGE_TYPE_METHOD_CALL message .
125
20
24,117
def new_method_return ( self ) : result = dbus . dbus_message_new_method_return ( self . _dbobj ) if result == None : raise CallFailed ( "dbus_message_new_method_return" ) #end if return type ( self ) ( result )
creates a new DBUS . MESSAGE_TYPE_METHOD_RETURN that is a reply to this Message .
66
26
24,118
def new_signal ( celf , path , iface , name ) : result = dbus . dbus_message_new_signal ( path . encode ( ) , iface . encode ( ) , name . encode ( ) ) if result == None : raise CallFailed ( "dbus_message_new_signal" ) #end if return celf ( result )
creates a new DBUS . MESSAGE_TYPE_SIGNAL message .
82
18
24,119
def copy ( self ) : result = dbus . dbus_message_copy ( self . _dbobj ) if result == None : raise CallFailed ( "dbus_message_copy" ) #end if return type ( self ) ( result )
creates a copy of this Message .
54
8
24,120
def iter_init ( self ) : iter = self . ExtractIter ( None ) if dbus . dbus_message_iter_init ( self . _dbobj , iter . _dbobj ) == 0 : iter . _nulliter = True #end if return iter
creates an iterator for extracting the arguments of the Message .
57
12
24,121
def iter_init_append ( self ) : iter = self . AppendIter ( None ) dbus . dbus_message_iter_init_append ( self . _dbobj , iter . _dbobj ) return iter
creates a Message . AppendIter for appending arguments to the Message .
48
16
24,122
def error_name ( self ) : result = dbus . dbus_message_get_error_name ( self . _dbobj ) if result != None : result = result . decode ( ) #end if return result
the error name for a DBUS . MESSAGE_TYPE_ERROR message .
47
18
24,123
def destination ( self ) : result = dbus . dbus_message_get_destination ( self . _dbobj ) if result != None : result = result . decode ( ) #end if return result
the bus name that the message is to be sent to .
44
12
24,124
def marshal ( self ) : buf = ct . POINTER ( ct . c_ubyte ) ( ) nr_bytes = ct . c_int ( ) if not dbus . dbus_message_marshal ( self . _dbobj , ct . byref ( buf ) , ct . byref ( nr_bytes ) ) : raise CallFailed ( "dbus_message_marshal" ) #end if result = bytearray ( nr_bytes . value ) ct . memmove ( ct . addressof ( ( ct . c_ubyte * nr_bytes . value ) . from_buffer ( result ) ) , buf , nr_bytes . value ) dbus . dbus_free ( buf ) return result
serializes this Message into the wire protocol format and returns a bytes object .
174
15
24,125
def cancel ( self ) : dbus . dbus_pending_call_cancel ( self . _dbobj ) if self . _awaiting != None : # This probably shouldn’t occur. Looking at the source of libdbus, # it doesn’t keep track of any “cancelled” state for the PendingCall, # it just detaches it from any notifications about an incoming reply. self . _awaiting . cancel ( )
tells libdbus you no longer care about the pending incoming message .
100
15
24,126
def set ( self , name , msg ) : dbus . dbus_set_error ( self . _dbobj , name . encode ( ) , b"%s" , msg . encode ( ) )
fills in the error name and message .
44
9
24,127
def parse ( celf , s ) : def from_string_elts ( celf , attrs , tree ) : elts = dict ( ( k , attrs [ k ] ) for k in attrs ) child_tags = dict ( ( childclass . tag_name , childclass ) for childclass in tuple ( celf . tag_elts . values ( ) ) + ( Introspection . Annotation , ) ) children = [ ] for child in tree : if child . tag not in child_tags : raise KeyError ( "unrecognized tag %s" % child . tag ) #end if childclass = child_tags [ child . tag ] childattrs = { } for attrname in childclass . tag_attrs : if hasattr ( childclass , "tag_attrs_optional" ) and attrname in childclass . tag_attrs_optional : childattrs [ attrname ] = child . attrib . get ( attrname , None ) else : if attrname not in child . attrib : raise ValueError ( "missing %s attribute for %s tag" % ( attrname , child . tag ) ) #end if childattrs [ attrname ] = child . attrib [ attrname ] #end if #end for if hasattr ( childclass , "attr_convert" ) : for attr in childclass . attr_convert : if attr in childattrs : childattrs [ attr ] = childclass . attr_convert [ attr ] ( childattrs [ attr ] ) #end if #end for #end if children . append ( from_string_elts ( childclass , childattrs , child ) ) #end for for child_tag , childclass in tuple ( celf . tag_elts . items ( ) ) + ( ( ) , ( ( "annotations" , Introspection . Annotation ) , ) ) [ tree . tag != "annotation" ] : for child in children : if isinstance ( child , childclass ) : if child_tag not in elts : elts [ child_tag ] = [ ] #end if elts [ child_tag ] . append ( child ) #end if #end for #end for return celf ( * * elts ) #end from_string_elts #begin parse tree = XMLElementTree . fromstring ( s ) assert tree . tag == "node" , "root of introspection tree must be <node> tag" return from_string_elts ( Introspection , { } , tree )
generates an Introspection tree from the given XML string description .
559
13
24,128
def unparse ( self , indent_step = 4 , max_linelen = 72 ) : out = io . StringIO ( ) def to_string ( obj , indent ) : tag_name = obj . tag_name attrs = [ ] for attrname in obj . tag_attrs : attr = getattr ( obj , attrname ) if attr != None : if isinstance ( attr , enum . Enum ) : attr = attr . value elif isinstance ( attr , Type ) : attr = unparse_signature ( attr ) elif not isinstance ( attr , str ) : raise TypeError ( "unexpected attribute type %s for %s" % ( type ( attr ) . __name__ , repr ( attr ) ) ) #end if attrs . append ( "%s=%s" % ( attrname , quote_xml_attr ( attr ) ) ) #end if #end for has_elts = ( sum ( len ( getattr ( obj , attrname ) ) for attrname in tuple ( obj . tag_elts . keys ( ) ) + ( ( ) , ( "annotations" , ) ) [ not isinstance ( obj , Introspection . Annotation ) ] ) != 0 ) out . write ( " " * indent + "<" + tag_name ) if ( max_linelen != None and indent + len ( tag_name ) + sum ( ( len ( s ) + 1 ) for s in attrs ) + 2 + int ( has_elts ) > max_linelen ) : out . write ( "\n" ) for attr in attrs : out . write ( " " * ( indent + indent_step ) ) out . write ( attr ) out . write ( "\n" ) #end for out . write ( " " * indent ) else : for attr in attrs : out . write ( " " ) out . write ( attr ) #end for #end if if not has_elts : out . write ( "/" ) #end if out . write ( ">\n" ) if has_elts : for attrname in sorted ( obj . tag_elts . keys ( ) ) + [ "annotations" ] : for elt in getattr ( obj , attrname ) : to_string ( elt , indent + indent_step ) #end for #end for out . write ( " " * indent + "</" + tag_name + ">\n" ) #end if #end to_string #begin unparse out . write ( DBUS . INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE ) out . write ( "<node" ) if self . name != None : out . write ( " name=%s" % quote_xml_attr ( self . name ) ) #end if out . write ( ">\n" ) for elt in self . interfaces : to_string ( elt , indent_step ) #end for for elt in self . nodes : to_string ( elt , indent_step ) #end for out . write ( "</node>\n" ) return out . getvalue ( )
returns an XML string description of this Introspection tree .
703
12
24,129
def as_error ( self ) : result = dbus . Error . init ( ) result . set ( self . args [ 0 ] , self . args [ 1 ] ) return result
fills in and returns an Error object that reports the specified error name and message .
38
17
24,130
async def release_name_async ( self , bus_name , error = None , timeout = DBUS . TIMEOUT_USE_DEFAULT ) : assert self . loop != None , "no event loop to attach coroutine to" return await self . connection . bus_release_name_async ( bus_name , error = error , timeout = timeout )
releases a registered bus name .
78
7
24,131
def DefaultAdapter ( self ) : default_adapter = None for obj in mockobject . objects . keys ( ) : if obj . startswith ( '/org/bluez/' ) and 'dev_' not in obj : default_adapter = obj if default_adapter : return dbus . ObjectPath ( default_adapter , variant_level = 1 ) else : raise dbus . exceptions . DBusException ( 'No such adapter.' , name = 'org.bluez.Error.NoSuchAdapter' )
Retrieve the default adapter
112
5
24,132
def ListAdapters ( self ) : adapters = [ ] for obj in mockobject . objects . keys ( ) : if obj . startswith ( '/org/bluez/' ) and 'dev_' not in obj : adapters . append ( dbus . ObjectPath ( obj , variant_level = 1 ) ) return dbus . Array ( adapters , variant_level = 1 )
List all known adapters
81
4
24,133
def CreateDevice ( self , device_address ) : device_name = 'dev_' + device_address . replace ( ':' , '_' ) . upper ( ) adapter_path = self . path path = adapter_path + '/' + device_name if path not in mockobject . objects : raise dbus . exceptions . DBusException ( 'Could not create device for %s.' % device_address , name = 'org.bluez.Error.Failed' ) adapter = mockobject . objects [ self . path ] adapter . EmitSignal ( ADAPTER_IFACE , 'DeviceCreated' , 'o' , [ dbus . ObjectPath ( path , variant_level = 1 ) ] ) return dbus . ObjectPath ( path , variant_level = 1 )
Create a new device
168
4
24,134
def AddDevice ( self , adapter_device_name , device_address , alias ) : device_name = 'dev_' + device_address . replace ( ':' , '_' ) . upper ( ) adapter_path = '/org/bluez/' + adapter_device_name path = adapter_path + '/' + device_name if adapter_path not in mockobject . objects : raise dbus . exceptions . DBusException ( 'No such adapter.' , name = 'org.bluez.Error.NoSuchAdapter' ) properties = { 'UUIDs' : dbus . Array ( [ ] , signature = 's' , variant_level = 1 ) , 'Blocked' : dbus . Boolean ( False , variant_level = 1 ) , 'Connected' : dbus . Boolean ( False , variant_level = 1 ) , 'LegacyPairing' : dbus . Boolean ( False , variant_level = 1 ) , 'Paired' : dbus . Boolean ( False , variant_level = 1 ) , 'Trusted' : dbus . Boolean ( False , variant_level = 1 ) , 'RSSI' : dbus . Int16 ( - 79 , variant_level = 1 ) , # arbitrary 'Adapter' : dbus . ObjectPath ( adapter_path , variant_level = 1 ) , 'Address' : dbus . String ( device_address , variant_level = 1 ) , 'Alias' : dbus . String ( alias , variant_level = 1 ) , 'Name' : dbus . String ( alias , variant_level = 1 ) , 'Class' : dbus . UInt32 ( 0x240404 , variant_level = 1 ) , # Audio, headset. 'Icon' : dbus . String ( 'audio-headset' , variant_level = 1 ) , } self . AddObject ( path , DEVICE_IFACE , # Properties properties , # Methods [ ( 'GetProperties' , '' , 'a{sv}' , 'ret = self.GetAll("org.bluez.Device")' ) , ( 'SetProperty' , 'sv' , '' , 'self.Set("org.bluez.Device", args[0], args[1]); ' 'self.EmitSignal("org.bluez.Device", "PropertyChanged",' ' "sv", [args[0], args[1]])' ) , ] ) manager = mockobject . objects [ '/' ] manager . EmitSignal ( OBJECT_MANAGER_IFACE , 'InterfacesAdded' , 'oa{sa{sv}}' , [ dbus . ObjectPath ( path , variant_level = 1 ) , { DEVICE_IFACE : properties } , ] ) adapter = mockobject . objects [ adapter_path ] adapter . EmitSignal ( ADAPTER_IFACE , 'DeviceFound' , 'sa{sv}' , [ properties [ 'Address' ] , properties , ] ) return path
Convenience method to add a Bluetooth device
642
9
24,135
def ListDevices ( self ) : devices = [ ] for obj in mockobject . objects . keys ( ) : if obj . startswith ( '/org/bluez/' ) and 'dev_' in obj : devices . append ( dbus . ObjectPath ( obj , variant_level = 1 ) ) return dbus . Array ( devices , variant_level = 1 )
List all known devices
80
4
24,136
def FindDevice ( self , address ) : for obj in mockobject . objects . keys ( ) : if obj . startswith ( '/org/bluez/' ) and 'dev_' in obj : o = mockobject . objects [ obj ] if o . props [ DEVICE_IFACE ] [ 'Address' ] == dbus . String ( address , variant_level = 1 ) : return obj raise dbus . exceptions . DBusException ( 'No such device.' , name = 'org.bluez.Error.NoSuchDevice' )
Find a specific device by bluetooth address .
117
9
24,137
def Connect ( self ) : device_path = self . path if device_path not in mockobject . objects : raise dbus . exceptions . DBusException ( 'No such device.' , name = 'org.bluez.Error.NoSuchDevice' ) device = mockobject . objects [ device_path ] device . props [ AUDIO_IFACE ] [ 'State' ] = dbus . String ( "connected" , variant_level = 1 ) device . EmitSignal ( AUDIO_IFACE , 'PropertyChanged' , 'sv' , [ 'State' , dbus . String ( "connected" , variant_level = 1 ) , ] ) device . props [ DEVICE_IFACE ] [ 'Connected' ] = dbus . Boolean ( True , variant_level = 1 ) device . EmitSignal ( DEVICE_IFACE , 'PropertyChanged' , 'sv' , [ 'Connected' , dbus . Boolean ( True , variant_level = 1 ) , ] )
Connect a device
216
3
24,138
def Disconnect ( self ) : device_path = self . path if device_path not in mockobject . objects : raise dbus . exceptions . DBusException ( 'No such device.' , name = 'org.bluez.Error.NoSuchDevice' ) device = mockobject . objects [ device_path ] try : device . props [ AUDIO_IFACE ] [ 'State' ] = dbus . String ( "disconnected" , variant_level = 1 ) device . EmitSignal ( AUDIO_IFACE , 'PropertyChanged' , 'sv' , [ 'State' , dbus . String ( "disconnected" , variant_level = 1 ) , ] ) except KeyError : pass device . props [ DEVICE_IFACE ] [ 'Connected' ] = dbus . Boolean ( False , variant_level = 1 ) device . EmitSignal ( DEVICE_IFACE , 'PropertyChanged' , 'sv' , [ 'Connected' , dbus . Boolean ( False , variant_level = 1 ) , ] )
Disconnect a device
226
4
24,139
def AddEthernetDevice ( self , device_name , iface_name , state ) : path = '/org/freedesktop/NetworkManager/Devices/' + device_name wired_props = { 'Carrier' : False , 'HwAddress' : dbus . String ( '78:DD:08:D2:3D:43' ) , 'PermHwAddress' : dbus . String ( '78:DD:08:D2:3D:43' ) , 'Speed' : dbus . UInt32 ( 0 ) } self . AddObject ( path , 'org.freedesktop.NetworkManager.Device.Wired' , wired_props , [ ] ) props = { 'DeviceType' : dbus . UInt32 ( 1 ) , 'State' : dbus . UInt32 ( state ) , 'Interface' : iface_name , 'ActiveConnection' : dbus . ObjectPath ( '/' ) , 'AvailableConnections' : dbus . Array ( [ ] , signature = 'o' ) , 'AutoConnect' : False , 'Managed' : True , 'Driver' : 'dbusmock' , 'IpInterface' : '' } obj = dbusmock . get_object ( path ) obj . AddProperties ( DEVICE_IFACE , props ) self . object_manager_emit_added ( path ) NM = dbusmock . get_object ( MANAGER_OBJ ) devices = NM . Get ( MANAGER_IFACE , 'Devices' ) devices . append ( path ) NM . Set ( MANAGER_IFACE , 'Devices' , devices ) NM . EmitSignal ( 'org.freedesktop.NetworkManager' , 'DeviceAdded' , 'o' , [ path ] ) return path
Add an ethernet device .
403
6
24,140
def AddWiFiDevice ( self , device_name , iface_name , state ) : path = '/org/freedesktop/NetworkManager/Devices/' + device_name self . AddObject ( path , WIRELESS_DEVICE_IFACE , { 'HwAddress' : dbus . String ( '11:22:33:44:55:66' ) , 'PermHwAddress' : dbus . String ( '11:22:33:44:55:66' ) , 'Bitrate' : dbus . UInt32 ( 5400 ) , 'Mode' : dbus . UInt32 ( 2 ) , 'WirelessCapabilities' : dbus . UInt32 ( 255 ) , 'AccessPoints' : dbus . Array ( [ ] , signature = 'o' ) , } , [ ( 'GetAccessPoints' , '' , 'ao' , 'ret = self.access_points' ) , ( 'GetAllAccessPoints' , '' , 'ao' , 'ret = self.access_points' ) , ( 'RequestScan' , 'a{sv}' , '' , '' ) , ] ) dev_obj = dbusmock . get_object ( path ) dev_obj . access_points = [ ] dev_obj . AddProperties ( DEVICE_IFACE , { 'ActiveConnection' : dbus . ObjectPath ( '/' ) , 'AvailableConnections' : dbus . Array ( [ ] , signature = 'o' ) , 'AutoConnect' : False , 'Managed' : True , 'Driver' : 'dbusmock' , 'DeviceType' : dbus . UInt32 ( 2 ) , 'State' : dbus . UInt32 ( state ) , 'Interface' : iface_name , 'IpInterface' : iface_name , } ) self . object_manager_emit_added ( path ) NM = dbusmock . get_object ( MANAGER_OBJ ) devices = NM . Get ( MANAGER_IFACE , 'Devices' ) devices . append ( path ) NM . Set ( MANAGER_IFACE , 'Devices' , devices ) NM . EmitSignal ( 'org.freedesktop.NetworkManager' , 'DeviceAdded' , 'o' , [ path ] ) return path
Add a WiFi Device .
511
5
24,141
def AddAccessPoint ( self , dev_path , ap_name , ssid , hw_address , mode , frequency , rate , strength , security ) : dev_obj = dbusmock . get_object ( dev_path ) ap_path = '/org/freedesktop/NetworkManager/AccessPoint/' + ap_name if ap_path in dev_obj . access_points : raise dbus . exceptions . DBusException ( 'Access point %s on device %s already exists' % ( ap_name , dev_path ) , name = MANAGER_IFACE + '.AlreadyExists' ) flags = NM80211ApFlags . NM_802_11_AP_FLAGS_PRIVACY if security == NM80211ApSecurityFlags . NM_802_11_AP_SEC_NONE : flags = NM80211ApFlags . NM_802_11_AP_FLAGS_NONE self . AddObject ( ap_path , ACCESS_POINT_IFACE , { 'Ssid' : dbus . ByteArray ( ssid . encode ( 'UTF-8' ) ) , 'HwAddress' : dbus . String ( hw_address ) , 'Flags' : dbus . UInt32 ( flags ) , 'LastSeen' : dbus . Int32 ( 1 ) , 'Frequency' : dbus . UInt32 ( frequency ) , 'MaxBitrate' : dbus . UInt32 ( rate ) , 'Mode' : dbus . UInt32 ( mode ) , 'RsnFlags' : dbus . UInt32 ( security ) , 'WpaFlags' : dbus . UInt32 ( security ) , 'Strength' : dbus . Byte ( strength ) } , [ ] ) self . object_manager_emit_added ( ap_path ) dev_obj . access_points . append ( ap_path ) aps = dev_obj . Get ( WIRELESS_DEVICE_IFACE , 'AccessPoints' ) aps . append ( ap_path ) dev_obj . Set ( WIRELESS_DEVICE_IFACE , 'AccessPoints' , aps ) dev_obj . EmitSignal ( WIRELESS_DEVICE_IFACE , 'AccessPointAdded' , 'o' , [ ap_path ] ) return ap_path
Add an access point to an existing WiFi device .
508
10
24,142
def AddActiveConnection ( self , devices , connection_device , specific_object , name , state ) : conn_obj = dbusmock . get_object ( connection_device ) settings = conn_obj . settings conn_uuid = settings [ 'connection' ] [ 'uuid' ] conn_type = settings [ 'connection' ] [ 'type' ] device_objects = [ dbus . ObjectPath ( dev ) for dev in devices ] active_connection_path = '/org/freedesktop/NetworkManager/ActiveConnection/' + name self . AddObject ( active_connection_path , ACTIVE_CONNECTION_IFACE , { 'Devices' : dbus . Array ( device_objects , signature = 'o' ) , 'Default6' : False , 'Default' : True , 'Type' : conn_type , 'Vpn' : ( conn_type == 'vpn' ) , 'Connection' : dbus . ObjectPath ( connection_device ) , 'Master' : dbus . ObjectPath ( '/' ) , 'SpecificObject' : dbus . ObjectPath ( specific_object ) , 'Uuid' : conn_uuid , 'State' : dbus . UInt32 ( state ) , } , [ ] ) for dev_path in devices : self . SetDeviceActive ( dev_path , active_connection_path ) self . object_manager_emit_added ( active_connection_path ) NM = dbusmock . get_object ( MANAGER_OBJ ) active_connections = NM . Get ( MANAGER_IFACE , 'ActiveConnections' ) active_connections . append ( dbus . ObjectPath ( active_connection_path ) ) NM . SetProperty ( MANAGER_OBJ , MANAGER_IFACE , 'ActiveConnections' , active_connections ) return active_connection_path
Add an active connection to an existing WiFi device .
409
10
24,143
def RemoveAccessPoint ( self , dev_path , ap_path ) : dev_obj = dbusmock . get_object ( dev_path ) aps = dev_obj . Get ( WIRELESS_DEVICE_IFACE , 'AccessPoints' ) aps . remove ( ap_path ) dev_obj . Set ( WIRELESS_DEVICE_IFACE , 'AccessPoints' , aps ) dev_obj . access_points . remove ( ap_path ) dev_obj . EmitSignal ( WIRELESS_DEVICE_IFACE , 'AccessPointRemoved' , 'o' , [ ap_path ] ) self . object_manager_emit_removed ( ap_path ) self . RemoveObject ( ap_path )
Remove the specified access point .
164
6
24,144
def RemoveWifiConnection ( self , dev_path , connection_path ) : dev_obj = dbusmock . get_object ( dev_path ) settings_obj = dbusmock . get_object ( SETTINGS_OBJ ) connections = dev_obj . Get ( DEVICE_IFACE , 'AvailableConnections' ) main_connections = settings_obj . ListConnections ( ) if connection_path not in connections and connection_path not in main_connections : return connections . remove ( dbus . ObjectPath ( connection_path ) ) dev_obj . Set ( DEVICE_IFACE , 'AvailableConnections' , connections ) main_connections . remove ( connection_path ) settings_obj . Set ( SETTINGS_IFACE , 'Connections' , main_connections ) settings_obj . EmitSignal ( SETTINGS_IFACE , 'ConnectionRemoved' , 'o' , [ connection_path ] ) connection_obj = dbusmock . get_object ( connection_path ) connection_obj . EmitSignal ( CSETTINGS_IFACE , 'Removed' , '' , [ ] ) self . object_manager_emit_removed ( connection_path ) self . RemoveObject ( connection_path )
Remove the specified WiFi connection .
275
6
24,145
def RemoveActiveConnection ( self , dev_path , active_connection_path ) : self . SetDeviceDisconnected ( dev_path ) NM = dbusmock . get_object ( MANAGER_OBJ ) active_connections = NM . Get ( MANAGER_IFACE , 'ActiveConnections' ) if active_connection_path not in active_connections : return active_connections . remove ( dbus . ObjectPath ( active_connection_path ) ) NM . SetProperty ( MANAGER_OBJ , MANAGER_IFACE , 'ActiveConnections' , active_connections ) self . object_manager_emit_removed ( active_connection_path ) self . RemoveObject ( active_connection_path )
Remove the specified ActiveConnection .
162
6
24,146
def SettingsAddConnection ( self , connection_settings ) : if 'uuid' not in connection_settings [ 'connection' ] : connection_settings [ 'connection' ] [ 'uuid' ] = str ( uuid . uuid4 ( ) ) NM = dbusmock . get_object ( MANAGER_OBJ ) settings_obj = dbusmock . get_object ( SETTINGS_OBJ ) main_connections = settings_obj . ListConnections ( ) # Mimic how NM names connections count = 0 while True : connection_obj_path = dbus . ObjectPath ( SETTINGS_OBJ + '/' + str ( count ) ) if connection_obj_path not in main_connections : break count += 1 connection_path = str ( connection_obj_path ) self . AddObject ( connection_path , CSETTINGS_IFACE , { 'Unsaved' : False } , [ ( 'Delete' , '' , '' , 'self.ConnectionDelete(self)' ) , ( 'GetSettings' , '' , 'a{sa{sv}}' , 'ret = self.ConnectionGetSettings(self)' ) , ( 'GetSecrets' , 's' , 'a{sa{sv}}' , 'ret = self.ConnectionGetSecrets(self, args[0])' ) , ( 'Update' , 'a{sa{sv}}' , '' , 'self.ConnectionUpdate(self, args[0])' ) , ] ) self . object_manager_emit_added ( connection_path ) connection_obj = dbusmock . get_object ( connection_path ) connection_obj . settings = connection_settings connection_obj . connection_path = connection_path connection_obj . ConnectionDelete = ConnectionDelete connection_obj . ConnectionGetSettings = ConnectionGetSettings connection_obj . ConnectionGetSecrets = ConnectionGetSecrets connection_obj . ConnectionUpdate = ConnectionUpdate main_connections . append ( connection_path ) settings_obj . Set ( SETTINGS_IFACE , 'Connections' , main_connections ) settings_obj . EmitSignal ( SETTINGS_IFACE , 'NewConnection' , 'o' , [ connection_path ] ) auto_connect = False if 'autoconnect' in connection_settings [ 'connection' ] : auto_connect = connection_settings [ 'connection' ] [ 'autoconnect' ] if auto_connect : dev = None devices = NM . GetDevices ( ) # Grab the first device. if len ( devices ) > 0 : dev = devices [ 0 ] if dev : activate_connection ( NM , connection_path , dev , connection_path ) return connection_path
Add a connection .
583
4
24,147
def ConnectionUpdate ( self , settings ) : connection_path = self . connection_path NM = dbusmock . get_object ( MANAGER_OBJ ) settings_obj = dbusmock . get_object ( SETTINGS_OBJ ) main_connections = settings_obj . ListConnections ( ) if connection_path not in main_connections : raise dbus . exceptions . DBusException ( 'Connection %s does not exist' % connection_path , name = MANAGER_IFACE + '.DoesNotExist' , ) # Take care not to overwrite the secrets for setting_name in settings : setting = settings [ setting_name ] for k in setting : if setting_name not in self . settings : self . settings [ setting_name ] = { } self . settings [ setting_name ] [ k ] = setting [ k ] self . EmitSignal ( CSETTINGS_IFACE , 'Updated' , '' , [ ] ) auto_connect = False if 'autoconnect' in settings [ 'connection' ] : auto_connect = settings [ 'connection' ] [ 'autoconnect' ] if auto_connect : dev = None devices = NM . GetDevices ( ) # Grab the first device. if len ( devices ) > 0 : dev = devices [ 0 ] if dev : activate_connection ( NM , connection_path , dev , connection_path ) return connection_path
Update settings on a connection .
306
6
24,148
def ConnectionDelete ( self ) : connection_path = self . connection_path NM = dbusmock . get_object ( MANAGER_OBJ ) settings_obj = dbusmock . get_object ( SETTINGS_OBJ ) # Find the associated active connection(s). active_connections = NM . Get ( MANAGER_IFACE , 'ActiveConnections' ) associated_active_connections = [ ] for ac in active_connections : ac_obj = dbusmock . get_object ( ac ) ac_con = ac_obj . Get ( ACTIVE_CONNECTION_IFACE , 'Connection' ) if ac_con == connection_path : associated_active_connections . append ( ac ) # We found that the connection we are deleting are associated to all # active connections and subsequently set the global state to # disconnected. if len ( active_connections ) == len ( associated_active_connections ) : self . SetGlobalConnectionState ( NMState . NM_STATE_DISCONNECTED ) # Remove the connection from all associated devices. # We also remove all associated active connections. for dev_path in NM . GetDevices ( ) : dev_obj = dbusmock . get_object ( dev_path ) connections = dev_obj . Get ( DEVICE_IFACE , 'AvailableConnections' ) for ac in associated_active_connections : NM . RemoveActiveConnection ( dev_path , ac ) if connection_path not in connections : continue connections . remove ( dbus . ObjectPath ( connection_path ) ) dev_obj . Set ( DEVICE_IFACE , 'AvailableConnections' , connections ) # Remove the connection from the settings interface main_connections = settings_obj . ListConnections ( ) if connection_path not in main_connections : return main_connections . remove ( connection_path ) settings_obj . Set ( SETTINGS_IFACE , 'Connections' , main_connections ) settings_obj . EmitSignal ( SETTINGS_IFACE , 'ConnectionRemoved' , 'o' , [ connection_path ] ) # Remove the connection from the mock connection_obj = dbusmock . get_object ( connection_path ) connection_obj . EmitSignal ( CSETTINGS_IFACE , 'Removed' , '' , [ ] ) self . object_manager_emit_removed ( connection_path ) self . RemoveObject ( connection_path )
Deletes a connection .
533
5
24,149
def AddAC ( self , device_name , model_name ) : path = '/org/freedesktop/UPower/devices/' + device_name self . AddObject ( path , DEVICE_IFACE , { 'PowerSupply' : dbus . Boolean ( True , variant_level = 1 ) , 'Model' : dbus . String ( model_name , variant_level = 1 ) , 'Online' : dbus . Boolean ( True , variant_level = 1 ) , } , [ ] ) self . EmitSignal ( MAIN_IFACE , 'DeviceAdded' , self . device_sig_type , [ path ] ) return path
Convenience method to add an AC object
145
9
24,150
def AddDischargingBattery ( self , device_name , model_name , percentage , seconds_to_empty ) : path = '/org/freedesktop/UPower/devices/' + device_name self . AddObject ( path , DEVICE_IFACE , { 'PowerSupply' : dbus . Boolean ( True , variant_level = 1 ) , 'IsPresent' : dbus . Boolean ( True , variant_level = 1 ) , 'Model' : dbus . String ( model_name , variant_level = 1 ) , 'Percentage' : dbus . Double ( percentage , variant_level = 1 ) , 'TimeToEmpty' : dbus . Int64 ( seconds_to_empty , variant_level = 1 ) , 'EnergyFull' : dbus . Double ( 100.0 , variant_level = 1 ) , 'Energy' : dbus . Double ( percentage , variant_level = 1 ) , # UP_DEVICE_STATE_DISCHARGING 'State' : dbus . UInt32 ( 2 , variant_level = 1 ) , # UP_DEVICE_KIND_BATTERY 'Type' : dbus . UInt32 ( 2 , variant_level = 1 ) , } , [ ] ) self . EmitSignal ( MAIN_IFACE , 'DeviceAdded' , self . device_sig_type , [ path ] ) return path
Convenience method to add a discharging battery object
303
11
24,151
def SetupDisplayDevice ( self , type , state , percentage , energy , energy_full , energy_rate , time_to_empty , time_to_full , is_present , icon_name , warning_level ) : if not self . api1 : raise dbus . exceptions . DBusException ( 'SetupDisplayDevice() can only be used with the 1.0 API' , name = MOCK_IFACE + '.APIVersion' ) display_props = mockobject . objects [ self . p_display_dev ] display_props . Set ( DEVICE_IFACE , 'Type' , dbus . UInt32 ( type ) ) display_props . Set ( DEVICE_IFACE , 'State' , dbus . UInt32 ( state ) ) display_props . Set ( DEVICE_IFACE , 'Percentage' , percentage ) display_props . Set ( DEVICE_IFACE , 'Energy' , energy ) display_props . Set ( DEVICE_IFACE , 'EnergyFull' , energy_full ) display_props . Set ( DEVICE_IFACE , 'EnergyRate' , energy_rate ) display_props . Set ( DEVICE_IFACE , 'TimeToEmpty' , dbus . Int64 ( time_to_empty ) ) display_props . Set ( DEVICE_IFACE , 'TimeToFull' , dbus . Int64 ( time_to_full ) ) display_props . Set ( DEVICE_IFACE , 'IsPresent' , is_present ) display_props . Set ( DEVICE_IFACE , 'IconName' , icon_name ) display_props . Set ( DEVICE_IFACE , 'WarningLevel' , dbus . UInt32 ( warning_level ) )
Convenience method to configure DisplayDevice properties
389
9
24,152
def SetDeviceProperties ( self , object_path , properties ) : device = dbusmock . get_object ( object_path ) # set the properties for key , value in properties . items ( ) : device . Set ( DEVICE_IFACE , key , value ) # notify the listeners if not self . api1 : self . EmitSignal ( MAIN_IFACE , 'DeviceChanged' , 's' , [ object_path ] )
Convenience method to Set a device s properties .
98
11
24,153
def AddSeat ( self , seat ) : seat_path = '/org/freedesktop/login1/seat/' + seat if seat_path in mockobject . objects : raise dbus . exceptions . DBusException ( 'Seat %s already exists' % seat , name = MOCK_IFACE + '.SeatExists' ) self . AddObject ( seat_path , 'org.freedesktop.login1.Seat' , { 'Sessions' : dbus . Array ( [ ] , signature = '(so)' ) , 'CanGraphical' : False , 'CanMultiSession' : True , 'CanTTY' : False , 'IdleHint' : False , 'ActiveSession' : ( '' , dbus . ObjectPath ( '/' ) ) , 'Id' : seat , 'IdleSinceHint' : dbus . UInt64 ( 0 ) , 'IdleSinceHintMonotonic' : dbus . UInt64 ( 0 ) , } , [ ( 'ActivateSession' , 's' , '' , '' ) , ( 'Terminate' , '' , '' , '' ) ] ) return seat_path
Convenience method to add a seat .
255
9
24,154
def AddUser ( self , uid , username , active ) : user_path = '/org/freedesktop/login1/user/%i' % uid if user_path in mockobject . objects : raise dbus . exceptions . DBusException ( 'User %i already exists' % uid , name = MOCK_IFACE + '.UserExists' ) self . AddObject ( user_path , 'org.freedesktop.login1.User' , { 'Sessions' : dbus . Array ( [ ] , signature = '(so)' ) , 'IdleHint' : False , 'DefaultControlGroup' : 'systemd:/user/' + username , 'Name' : username , 'RuntimePath' : '/run/user/%i' % uid , 'Service' : '' , 'State' : ( active and 'active' or 'online' ) , 'Display' : ( '' , dbus . ObjectPath ( '/' ) ) , 'UID' : dbus . UInt32 ( uid ) , 'GID' : dbus . UInt32 ( uid ) , 'IdleSinceHint' : dbus . UInt64 ( 0 ) , 'IdleSinceHintMonotonic' : dbus . UInt64 ( 0 ) , 'Timestamp' : dbus . UInt64 ( 42 ) , 'TimestampMonotonic' : dbus . UInt64 ( 42 ) , } , [ ( 'Kill' , 's' , '' , '' ) , ( 'Terminate' , '' , '' , '' ) , ] ) return user_path
Convenience method to add a user .
353
9
24,155
def AddSession ( self , session_id , seat , uid , username , active ) : seat_path = dbus . ObjectPath ( '/org/freedesktop/login1/seat/' + seat ) if seat_path not in mockobject . objects : self . AddSeat ( seat ) user_path = dbus . ObjectPath ( '/org/freedesktop/login1/user/%i' % uid ) if user_path not in mockobject . objects : self . AddUser ( uid , username , active ) session_path = dbus . ObjectPath ( '/org/freedesktop/login1/session/' + session_id ) if session_path in mockobject . objects : raise dbus . exceptions . DBusException ( 'Session %s already exists' % session_id , name = MOCK_IFACE + '.SessionExists' ) self . AddObject ( session_path , 'org.freedesktop.login1.Session' , { 'Controllers' : dbus . Array ( [ ] , signature = 's' ) , 'ResetControllers' : dbus . Array ( [ ] , signature = 's' ) , 'Active' : active , 'IdleHint' : False , 'KillProcesses' : False , 'Remote' : False , 'Class' : 'user' , 'DefaultControlGroup' : 'systemd:/user/%s/%s' % ( username , session_id ) , 'Display' : os . getenv ( 'DISPLAY' , '' ) , 'Id' : session_id , 'Name' : username , 'RemoteHost' : '' , 'RemoteUser' : '' , 'Service' : 'dbusmock' , 'State' : ( active and 'active' or 'online' ) , 'TTY' : '' , 'Type' : 'test' , 'Seat' : ( seat , seat_path ) , 'User' : ( dbus . UInt32 ( uid ) , user_path ) , 'Audit' : dbus . UInt32 ( 0 ) , 'Leader' : dbus . UInt32 ( 1 ) , 'VTNr' : dbus . UInt32 ( 1 ) , 'IdleSinceHint' : dbus . UInt64 ( 0 ) , 'IdleSinceHintMonotonic' : dbus . UInt64 ( 0 ) , 'Timestamp' : dbus . UInt64 ( 42 ) , 'TimestampMonotonic' : dbus . UInt64 ( 42 ) , } , [ ( 'Activate' , '' , '' , '' ) , ( 'Kill' , 'ss' , '' , '' ) , ( 'Lock' , '' , '' , '' ) , ( 'SetIdleHint' , 'b' , '' , '' ) , ( 'Terminate' , '' , '' , '' ) , ( 'Unlock' , '' , '' , '' ) , ] ) # add session to seat obj_seat = mockobject . objects [ seat_path ] cur_sessions = obj_seat . Get ( 'org.freedesktop.login1.Seat' , 'Sessions' ) cur_sessions . append ( ( session_id , session_path ) ) obj_seat . Set ( 'org.freedesktop.login1.Seat' , 'Sessions' , cur_sessions ) obj_seat . Set ( 'org.freedesktop.login1.Seat' , 'ActiveSession' , ( session_id , session_path ) ) # add session to user obj_user = mockobject . objects [ user_path ] cur_sessions = obj_user . Get ( 'org.freedesktop.login1.User' , 'Sessions' ) cur_sessions . append ( ( session_id , session_path ) ) obj_user . Set ( 'org.freedesktop.login1.User' , 'Sessions' , cur_sessions ) return session_path
Convenience method to add a session .
882
9
24,156
def _set_up_object_manager ( self ) : if self . path == '/' : cond = 'k != \'/\'' else : cond = 'k.startswith(\'%s/\')' % self . path self . AddMethod ( OBJECT_MANAGER_IFACE , 'GetManagedObjects' , '' , 'a{oa{sa{sv}}}' , 'ret = {dbus.ObjectPath(k): objects[k].props ' + ' for k in objects.keys() if ' + cond + '}' ) self . object_manager = self
Set up this mock object as a D - Bus ObjectManager .
132
13
24,157
def Get ( self , interface_name , property_name ) : self . log ( 'Get %s.%s' % ( interface_name , property_name ) ) if not interface_name : interface_name = self . interface try : return self . GetAll ( interface_name ) [ property_name ] except KeyError : raise dbus . exceptions . DBusException ( 'no such property ' + property_name , name = self . interface + '.UnknownProperty' )
Standard D - Bus API for getting a property value
102
10
24,158
def GetAll ( self , interface_name , * args , * * kwargs ) : self . log ( 'GetAll ' + interface_name ) if not interface_name : interface_name = self . interface try : return self . props [ interface_name ] except KeyError : raise dbus . exceptions . DBusException ( 'no such interface ' + interface_name , name = self . interface + '.UnknownInterface' )
Standard D - Bus API for getting all property values
92
10
24,159
def Set ( self , interface_name , property_name , value , * args , * * kwargs ) : self . log ( 'Set %s.%s%s' % ( interface_name , property_name , self . format_args ( ( value , ) ) ) ) try : iface_props = self . props [ interface_name ] except KeyError : raise dbus . exceptions . DBusException ( 'no such interface ' + interface_name , name = self . interface + '.UnknownInterface' ) if property_name not in iface_props : raise dbus . exceptions . DBusException ( 'no such property ' + property_name , name = self . interface + '.UnknownProperty' ) iface_props [ property_name ] = value self . EmitSignal ( 'org.freedesktop.DBus.Properties' , 'PropertiesChanged' , 'sa{sv}as' , [ interface_name , dbus . Dictionary ( { property_name : value } , signature = 'sv' ) , dbus . Array ( [ ] , signature = 's' ) ] )
Standard D - Bus API for setting a property value
245
10
24,160
def AddObject ( self , path , interface , properties , methods ) : if path in objects : raise dbus . exceptions . DBusException ( 'object %s already exists' % path , name = 'org.freedesktop.DBus.Mock.NameError' ) obj = DBusMockObject ( self . bus_name , path , interface , properties ) # make sure created objects inherit the log file stream obj . logfile = self . logfile obj . object_manager = self . object_manager obj . is_logfile_owner = False obj . AddMethods ( interface , methods ) objects [ path ] = obj
Add a new D - Bus object to the mock
135
10
24,161
def RemoveObject ( self , path ) : try : objects [ path ] . remove_from_connection ( ) del objects [ path ] except KeyError : raise dbus . exceptions . DBusException ( 'object %s does not exist' % path , name = 'org.freedesktop.DBus.Mock.NameError' )
Remove a D - Bus object from the mock
73
9
24,162
def Reset ( self ) : # Clear other existing objects. for obj_name , obj in objects . items ( ) : if obj_name != self . path : obj . remove_from_connection ( ) objects . clear ( ) # Reinitialise our state. Carefully remove new methods from our dict; # they don't not actually exist if they are a statically defined # template function for method_name in self . methods [ self . interface ] : try : delattr ( self . __class__ , method_name ) except AttributeError : pass self . _reset ( { } ) if self . _template is not None : self . AddTemplate ( self . _template , self . _template_parameters ) objects [ self . path ] = self
Reset the mock object state .
158
7
24,163
def AddMethod ( self , interface , name , in_sig , out_sig , code ) : if not interface : interface = self . interface n_args = len ( dbus . Signature ( in_sig ) ) # we need to have separate methods for dbus-python, so clone # mock_method(); using message_keyword with this dynamic approach fails # because inspect cannot handle those, so pass on interface and method # name as first positional arguments method = lambda self , * args , * * kwargs : DBusMockObject . mock_method ( self , interface , name , in_sig , * args , * * kwargs ) # we cannot specify in_signature here, as that trips over a consistency # check in dbus-python; we need to set it manually instead dbus_method = dbus . service . method ( interface , out_signature = out_sig ) ( method ) dbus_method . __name__ = str ( name ) dbus_method . _dbus_in_signature = in_sig dbus_method . _dbus_args = [ 'arg%i' % i for i in range ( 1 , n_args + 1 ) ] # for convenience, add mocked methods on the primary interface as # callable methods if interface == self . interface : setattr ( self . __class__ , name , dbus_method ) self . methods . setdefault ( interface , { } ) [ str ( name ) ] = ( in_sig , out_sig , code , dbus_method )
Add a method to this object
340
6
24,164
def AddMethods ( self , interface , methods ) : for method in methods : self . AddMethod ( interface , * method )
Add several methods to this object
26
6
24,165
def AddProperty ( self , interface , name , value ) : if not interface : interface = self . interface try : self . props [ interface ] [ name ] raise dbus . exceptions . DBusException ( 'property %s already exists' % name , name = self . interface + '.PropertyExists' ) except KeyError : # this is what we expect pass # copy.copy removes one level of variant-ness, which means that the # types get exported in introspection data correctly, but we can't do # this for container types. if not ( isinstance ( value , dbus . Dictionary ) or isinstance ( value , dbus . Array ) ) : value = copy . copy ( value ) self . props . setdefault ( interface , { } ) [ name ] = value
Add property to this object
164
5
24,166
def AddProperties ( self , interface , properties ) : for k , v in properties . items ( ) : self . AddProperty ( interface , k , v )
Add several properties to this object
34
6
24,167
def AddTemplate ( self , template , parameters ) : try : module = load_module ( template ) except ImportError as e : raise dbus . exceptions . DBusException ( 'Cannot add template %s: %s' % ( template , str ( e ) ) , name = 'org.freedesktop.DBus.Mock.TemplateError' ) # If the template specifies this is an ObjectManager, set that up if hasattr ( module , 'IS_OBJECT_MANAGER' ) and module . IS_OBJECT_MANAGER : self . _set_up_object_manager ( ) # pick out all D-Bus service methods and add them to our interface for symbol in dir ( module ) : fn = getattr ( module , symbol ) if ( '_dbus_interface' in dir ( fn ) and ( '_dbus_is_signal' not in dir ( fn ) or not fn . _dbus_is_signal ) ) : # for dbus-python compatibility, add methods as callables setattr ( self . __class__ , symbol , fn ) self . methods . setdefault ( fn . _dbus_interface , { } ) [ str ( symbol ) ] = ( fn . _dbus_in_signature , fn . _dbus_out_signature , '' , fn ) if parameters is None : parameters = { } module . load ( self , parameters ) # save the given template and parameters for re-instantiation on # Reset() self . _template = template self . _template_parameters = parameters
Load a template into the mock .
339
7
24,168
def EmitSignal ( self , interface , name , signature , args ) : if not interface : interface = self . interface # convert types of arguments according to signature, using # MethodCallMessage.append(); this will also provide type/length # checks, except for the case of an empty signature if signature == '' and len ( args ) > 0 : raise TypeError ( 'Fewer items found in D-Bus signature than in Python arguments' ) m = dbus . connection . MethodCallMessage ( 'a.b' , '/a' , 'a.b' , 'a' ) m . append ( signature = signature , * args ) args = m . get_args_list ( ) fn = lambda self , * args : self . log ( 'emit %s.%s%s' % ( interface , name , self . format_args ( args ) ) ) fn . __name__ = str ( name ) dbus_fn = dbus . service . signal ( interface ) ( fn ) dbus_fn . _dbus_signature = signature dbus_fn . _dbus_args = [ 'arg%i' % i for i in range ( 1 , len ( args ) + 1 ) ] dbus_fn ( self , * args )
Emit a signal from the object .
269
8
24,169
def GetMethodCalls ( self , method ) : return [ ( row [ 0 ] , row [ 2 ] ) for row in self . call_log if row [ 1 ] == method ]
List all the logged calls of a particular method .
40
10
24,170
def mock_method ( self , interface , dbus_method , in_signature , * args , * * kwargs ) : # print('mock_method', dbus_method, self, in_signature, args, kwargs, file=sys.stderr) # convert types of arguments according to signature, using # MethodCallMessage.append(); this will also provide type/length # checks, except for the case of an empty signature if in_signature == '' and len ( args ) > 0 : raise TypeError ( 'Fewer items found in D-Bus signature than in Python arguments' ) m = dbus . connection . MethodCallMessage ( 'a.b' , '/a' , 'a.b' , 'a' ) m . append ( signature = in_signature , * args ) args = m . get_args_list ( ) self . log ( dbus_method + self . format_args ( args ) ) self . call_log . append ( ( int ( time . time ( ) ) , str ( dbus_method ) , args ) ) self . MethodCalled ( dbus_method , args ) # The code may be a Python 3 string to interpret, or may be a function # object (if AddMethod was called from within Python itself, rather than # over D-Bus). code = self . methods [ interface ] [ dbus_method ] [ 2 ] if code and isinstance ( code , types . FunctionType ) : return code ( self , * args ) elif code : loc = locals ( ) . copy ( ) exec ( code , globals ( ) , loc ) if 'ret' in loc : return loc [ 'ret' ]
Master mock method .
364
4
24,171
def format_args ( self , args ) : def format_arg ( a ) : if isinstance ( a , dbus . Boolean ) : return str ( bool ( a ) ) if isinstance ( a , dbus . Byte ) : return str ( int ( a ) ) if isinstance ( a , int ) or isinstance ( a , long ) : return str ( a ) if isinstance ( a , str ) : return '"' + str ( a ) + '"' if isinstance ( a , unicode ) : # Python 2 only return '"' + repr ( a . encode ( 'UTF-8' ) ) [ 1 : - 1 ] + '"' if isinstance ( a , list ) : return '[' + ', ' . join ( [ format_arg ( x ) for x in a ] ) + ']' if isinstance ( a , dict ) : fmta = '{' first = True for k , v in a . items ( ) : if first : first = False else : fmta += ', ' fmta += format_arg ( k ) + ': ' + format_arg ( v ) return fmta + '}' # fallback return repr ( a ) s = '' for a in args : if s : s += ' ' s += format_arg ( a ) if s : s = ' ' + s return s
Format a D - Bus argument tuple into an appropriate logging string .
289
13
24,172
def log ( self , msg ) : if self . logfile : fd = self . logfile . fileno ( ) else : fd = sys . stdout . fileno ( ) os . write ( fd , ( '%.3f %s\n' % ( time . time ( ) , msg ) ) . encode ( 'UTF-8' ) )
Log a message prefixed with a timestamp .
78
9
24,173
def Introspect ( self , object_path , connection ) : # temporarily add our dynamic methods cls = self . __class__ . __module__ + '.' + self . __class__ . __name__ orig_interfaces = self . _dbus_class_table [ cls ] mock_interfaces = orig_interfaces . copy ( ) for interface , methods in self . methods . items ( ) : for method in methods : mock_interfaces . setdefault ( interface , { } ) [ method ] = self . methods [ interface ] [ method ] [ 3 ] self . _dbus_class_table [ cls ] = mock_interfaces xml = dbus . service . Object . Introspect ( self , object_path , connection ) tree = ElementTree . fromstring ( xml ) for name in self . props : # We might have properties for new interfaces we don't know about # yet. Try to find an existing <interface> node named after our # interface to append to, and create one if we can't. interface = tree . find ( ".//interface[@name='%s']" % name ) if interface is None : interface = ElementTree . Element ( "interface" , { "name" : name } ) tree . append ( interface ) for prop , val in self . props [ name ] . items ( ) : if val is None : # can't guess type from None, skip continue elem = ElementTree . Element ( "property" , { "name" : prop , # We don't store the signature anywhere, so guess it. "type" : dbus . lowlevel . Message . guess_signature ( val ) , "access" : "readwrite" } ) interface . append ( elem ) xml = ElementTree . tostring ( tree , encoding = 'utf8' , method = 'xml' ) . decode ( 'utf8' ) # restore original class table self . _dbus_class_table [ cls ] = orig_interfaces return xml
Return XML description of this object s interfaces methods and signals .
425
12
24,174
def CreateSession ( self , destination , args ) : if 'Target' not in args or args [ 'Target' ] . upper ( ) != 'PBAP' : raise dbus . exceptions . DBusException ( 'Non-PBAP targets are not currently supported by this python-dbusmock template.' , name = OBEX_MOCK_IFACE + '.Unsupported' ) # Find the first unused session ID. client_path = '/org/bluez/obex/client' session_id = 0 while client_path + '/session' + str ( session_id ) in mockobject . objects : session_id += 1 path = client_path + '/session' + str ( session_id ) properties = { 'Source' : dbus . String ( 'FIXME' , variant_level = 1 ) , 'Destination' : dbus . String ( destination , variant_level = 1 ) , 'Channel' : dbus . Byte ( 0 , variant_level = 1 ) , 'Target' : dbus . String ( 'FIXME' , variant_level = 1 ) , 'Root' : dbus . String ( 'FIXME' , variant_level = 1 ) , } self . AddObject ( path , SESSION_IFACE , # Properties properties , # Methods [ ( 'GetCapabilities' , '' , 's' , '' ) , # Currently a no-op ] ) session = mockobject . objects [ path ] session . AddMethods ( PHONEBOOK_ACCESS_IFACE , [ ( 'Select' , 'ss' , '' , '' ) , # Currently a no-op # Currently a no-op ( 'List' , 'a{sv}' , 'a(ss)' , 'ret = dbus.Array(signature="(ss)")' ) , # Currently a no-op ( 'ListFilterFields' , '' , 'as' , 'ret = dbus.Array(signature="(s)")' ) , ( 'PullAll' , 'sa{sv}' , 'sa{sv}' , PullAll ) , ( 'GetSize' , '' , 'q' , 'ret = 0' ) , # TODO ] ) manager = mockobject . objects [ '/' ] manager . EmitSignal ( OBJECT_MANAGER_IFACE , 'InterfacesAdded' , 'oa{sa{sv}}' , [ dbus . ObjectPath ( path ) , { SESSION_IFACE : properties } , ] ) return path
OBEX method to create a new transfer session .
539
10
24,175
def RemoveSession ( self , session_path ) : manager = mockobject . objects [ '/' ] # Remove all the session's transfers. transfer_id = 0 while session_path + '/transfer' + str ( transfer_id ) in mockobject . objects : transfer_path = session_path + '/transfer' + str ( transfer_id ) transfer_id += 1 self . RemoveObject ( transfer_path ) manager . EmitSignal ( OBJECT_MANAGER_IFACE , 'InterfacesRemoved' , 'oas' , [ dbus . ObjectPath ( transfer_path ) , [ TRANSFER_IFACE ] , ] ) # Remove the session itself. self . RemoveObject ( session_path ) manager . EmitSignal ( OBJECT_MANAGER_IFACE , 'InterfacesRemoved' , 'oas' , [ dbus . ObjectPath ( session_path ) , [ SESSION_IFACE , PHONEBOOK_ACCESS_IFACE ] , ] )
OBEX method to remove an existing transfer session .
212
10
24,176
def PullAll ( self , target_file , filters ) : # Find the first unused session ID. session_path = self . path transfer_id = 0 while session_path + '/transfer' + str ( transfer_id ) in mockobject . objects : transfer_id += 1 transfer_path = session_path + '/transfer' + str ( transfer_id ) # Create a new temporary file to transfer to. temp_file = tempfile . NamedTemporaryFile ( suffix = '.vcf' , prefix = 'tmp-bluez5-obex-PullAll_' , delete = False ) filename = os . path . abspath ( temp_file . name ) props = { 'Status' : dbus . String ( 'queued' , variant_level = 1 ) , 'Session' : dbus . ObjectPath ( session_path , variant_level = 1 ) , 'Name' : dbus . String ( target_file , variant_level = 1 ) , 'Filename' : dbus . String ( filename , variant_level = 1 ) , 'Transferred' : dbus . UInt64 ( 0 , variant_level = 1 ) , } self . AddObject ( transfer_path , TRANSFER_IFACE , # Properties props , # Methods [ ( 'Cancel' , '' , '' , '' ) , # Currently a no-op ] ) transfer = mockobject . objects [ transfer_path ] transfer . AddMethods ( TRANSFER_MOCK_IFACE , [ ( 'UpdateStatus' , 'b' , '' , UpdateStatus ) , ] ) manager = mockobject . objects [ '/' ] manager . EmitSignal ( OBJECT_MANAGER_IFACE , 'InterfacesAdded' , 'oa{sa{sv}}' , [ dbus . ObjectPath ( transfer_path ) , { TRANSFER_IFACE : props } , ] ) # Emit a behind-the-scenes signal that a new transfer has been created. manager . EmitSignal ( OBEX_MOCK_IFACE , 'TransferCreated' , 'sa{sv}s' , [ transfer_path , filters , filename ] ) return ( transfer_path , props )
OBEX method to start a pull transfer of a phone book .
465
13
24,177
def UpdateStatus ( self , is_complete ) : status = 'complete' if is_complete else 'active' transferred = os . path . getsize ( self . props [ TRANSFER_IFACE ] [ 'Filename' ] ) self . props [ TRANSFER_IFACE ] [ 'Status' ] = status self . props [ TRANSFER_IFACE ] [ 'Transferred' ] = dbus . UInt64 ( transferred , variant_level = 1 ) self . EmitSignal ( dbus . PROPERTIES_IFACE , 'PropertiesChanged' , 'sa{sv}as' , [ TRANSFER_IFACE , { 'Status' : dbus . String ( status , variant_level = 1 ) , 'Transferred' : dbus . UInt64 ( transferred , variant_level = 1 ) , } , [ ] , ] )
Mock method to update the transfer status .
184
9
24,178
def AddModem ( self , name , properties ) : path = '/' + name self . AddObject ( path , 'org.ofono.Modem' , { 'Online' : dbus . Boolean ( True , variant_level = 1 ) , 'Powered' : dbus . Boolean ( True , variant_level = 1 ) , 'Lockdown' : dbus . Boolean ( False , variant_level = 1 ) , 'Emergency' : dbus . Boolean ( False , variant_level = 1 ) , 'Manufacturer' : dbus . String ( 'Fakesys' , variant_level = 1 ) , 'Model' : dbus . String ( 'Mock Modem' , variant_level = 1 ) , 'Revision' : dbus . String ( '0815.42' , variant_level = 1 ) , 'Serial' : dbus . String ( new_modem_serial ( self ) , variant_level = 1 ) , 'Type' : dbus . String ( 'hardware' , variant_level = 1 ) , 'Interfaces' : [ 'org.ofono.CallVolume' , 'org.ofono.VoiceCallManager' , 'org.ofono.NetworkRegistration' , 'org.ofono.SimManager' , # 'org.ofono.MessageManager', 'org.ofono.ConnectionManager' , # 'org.ofono.NetworkTime' ] , # 'Features': ['sms', 'net', 'gprs', 'sim'] 'Features' : [ 'gprs' , 'net' ] , } , [ ( 'GetProperties' , '' , 'a{sv}' , 'ret = self.GetAll("org.ofono.Modem")' ) , ( 'SetProperty' , 'sv' , '' , 'self.Set("org.ofono.Modem", args[0], args[1]); ' 'self.EmitSignal("org.ofono.Modem", "PropertyChanged",' ' "sv", [args[0], args[1]])' ) , ] ) obj = dbusmock . mockobject . objects [ path ] obj . name = name add_voice_call_api ( obj ) add_netreg_api ( obj ) add_simmanager_api ( self , obj ) add_connectionmanager_api ( obj ) self . modems . append ( path ) props = obj . GetAll ( 'org.ofono.Modem' , dbus_interface = dbus . PROPERTIES_IFACE ) self . EmitSignal ( MAIN_IFACE , 'ModemAdded' , 'oa{sv}' , [ path , props ] ) return path
Convenience method to add a modem
586
8
24,179
def add_voice_call_api ( mock ) : # also add an emergency number which is not a real one, in case one runs a # test case against a production ofono :-) mock . AddProperty ( 'org.ofono.VoiceCallManager' , 'EmergencyNumbers' , [ '911' , '13373' ] ) mock . calls = [ ] # object paths mock . AddMethods ( 'org.ofono.VoiceCallManager' , [ ( 'GetProperties' , '' , 'a{sv}' , 'ret = self.GetAll("org.ofono.VoiceCallManager")' ) , ( 'Transfer' , '' , '' , '' ) , ( 'SwapCalls' , '' , '' , '' ) , ( 'ReleaseAndAnswer' , '' , '' , '' ) , ( 'ReleaseAndSwap' , '' , '' , '' ) , ( 'HoldAndAnswer' , '' , '' , '' ) , ( 'SendTones' , 's' , '' , '' ) , ( 'PrivateChat' , 'o' , 'ao' , NOT_IMPLEMENTED ) , ( 'CreateMultiparty' , '' , 'o' , NOT_IMPLEMENTED ) , ( 'HangupMultiparty' , '' , '' , NOT_IMPLEMENTED ) , ( 'GetCalls' , '' , 'a(oa{sv})' , 'ret = [(c, objects[c].GetAll("org.ofono.VoiceCall")) for c in self.calls]' ) ] )
Add org . ofono . VoiceCallManager API to a mock
335
13
24,180
def add_netreg_api ( mock ) : # also add an emergency number which is not a real one, in case one runs a # test case against a production ofono :-) mock . AddProperties ( 'org.ofono.NetworkRegistration' , { 'Mode' : 'auto' , 'Status' : 'registered' , 'LocationAreaCode' : _parameters . get ( 'LocationAreaCode' , 987 ) , 'CellId' : _parameters . get ( 'CellId' , 10203 ) , 'MobileCountryCode' : _parameters . get ( 'MobileCountryCode' , '777' ) , 'MobileNetworkCode' : _parameters . get ( 'MobileNetworkCode' , '11' ) , 'Technology' : _parameters . get ( 'Technology' , 'gsm' ) , 'Name' : _parameters . get ( 'Name' , 'fake.tel' ) , 'Strength' : _parameters . get ( 'Strength' , dbus . Byte ( 80 ) ) , 'BaseStation' : _parameters . get ( 'BaseStation' , '' ) , } ) mock . AddObject ( '/%s/operator/op1' % mock . name , 'org.ofono.NetworkOperator' , { 'Name' : _parameters . get ( 'Name' , 'fake.tel' ) , 'Status' : 'current' , 'MobileCountryCode' : _parameters . get ( 'MobileCountryCode' , '777' ) , 'MobileNetworkCode' : _parameters . get ( 'MobileNetworkCode' , '11' ) , 'Technologies' : [ _parameters . get ( 'Technology' , 'gsm' ) ] , } , [ ( 'GetProperties' , '' , 'a{sv}' , 'ret = self.GetAll("org.ofono.NetworkOperator")' ) , ( 'Register' , '' , '' , '' ) , ] # noqa: silly pep8 error here about hanging indent ) mock . AddMethods ( 'org.ofono.NetworkRegistration' , [ ( 'GetProperties' , '' , 'a{sv}' , 'ret = self.GetAll("org.ofono.NetworkRegistration")' ) , ( 'SetProperty' , 'sv' , '' , 'self.Set("%(i)s", args[0], args[1]); ' 'self.EmitSignal("%(i)s", "PropertyChanged", "sv", [args[0], args[1]])' % { 'i' : 'org.ofono.NetworkRegistration' } ) , ( 'Register' , '' , '' , '' ) , ( 'GetOperators' , '' , 'a(oa{sv})' , get_all_operators ( mock ) ) , ( 'Scan' , '' , 'a(oa{sv})' , get_all_operators ( mock ) ) , ] )
Add org . ofono . NetworkRegistration API to a mock
641
12
24,181
def add_connectionmanager_api ( mock ) : iface = 'org.ofono.ConnectionManager' mock . AddProperties ( iface , { 'Attached' : _parameters . get ( 'Attached' , True ) , 'Bearer' : _parameters . get ( 'Bearer' , 'gprs' ) , 'RoamingAllowed' : _parameters . get ( 'RoamingAllowed' , False ) , 'Powered' : _parameters . get ( 'ConnectionPowered' , True ) , } ) mock . AddMethods ( iface , [ ( 'GetProperties' , '' , 'a{sv}' , 'ret = self.GetAll("%s")' % iface ) , ( 'SetProperty' , 'sv' , '' , 'self.Set("%(i)s", args[0], args[1]); ' 'self.EmitSignal("%(i)s", "PropertyChanged", "sv", [args[0], args[1]])' % { 'i' : iface } ) , ( 'AddContext' , 's' , 'o' , 'ret = "/"' ) , ( 'RemoveContext' , 'o' , '' , '' ) , ( 'DeactivateAll' , '' , '' , '' ) , ( 'GetContexts' , '' , 'a(oa{sv})' , 'ret = dbus.Array([])' ) , ] )
Add org . ofono . ConnectionManager API to a mock
316
12
24,182
def BlockDevice ( self , adapter_device_name , device_address ) : device_name = 'dev_' + device_address . replace ( ':' , '_' ) . upper ( ) adapter_path = '/org/bluez/' + adapter_device_name device_path = adapter_path + '/' + device_name if adapter_path not in mockobject . objects : raise dbus . exceptions . DBusException ( 'Adapter %s does not exist.' % adapter_device_name , name = BLUEZ_MOCK_IFACE + '.NoSuchAdapter' ) if device_path not in mockobject . objects : raise dbus . exceptions . DBusException ( 'Device %s does not exist.' % device_name , name = BLUEZ_MOCK_IFACE + '.NoSuchDevice' ) device = mockobject . objects [ device_path ] device . props [ DEVICE_IFACE ] [ 'Blocked' ] = dbus . Boolean ( True , variant_level = 1 ) device . props [ DEVICE_IFACE ] [ 'Connected' ] = dbus . Boolean ( False , variant_level = 1 ) device . EmitSignal ( dbus . PROPERTIES_IFACE , 'PropertiesChanged' , 'sa{sv}as' , [ DEVICE_IFACE , { 'Blocked' : dbus . Boolean ( True , variant_level = 1 ) , 'Connected' : dbus . Boolean ( False , variant_level = 1 ) , } , [ ] , ] )
Convenience method to mark an existing device as blocked .
336
12
24,183
def create ( self , instance , errors ) : if errors : return self . errors ( errors ) return self . created ( instance )
Create an instance of a model .
27
7
24,184
def patch ( self , instance , errors ) : if errors : return self . errors ( errors ) return self . updated ( instance )
Partially update a model instance .
27
7
24,185
def put ( self , instance , errors ) : if errors : return self . errors ( errors ) return self . updated ( instance )
Update a model instance .
27
5
24,186
def before_init_app ( self , app : FlaskUnchained ) : from . templates import ( UnchainedJinjaEnvironment , UnchainedJinjaLoader ) app . jinja_environment = UnchainedJinjaEnvironment app . jinja_options = { * * app . jinja_options , 'loader' : UnchainedJinjaLoader ( app ) } app . jinja_env . globals [ 'url_for' ] = url_for for name in [ 'string' , 'str' ] : app . url_map . converters [ name ] = StringConverter
Configure the Jinja environment and template loader .
133
10
24,187
def after_init_app ( self , app : FlaskUnchained ) : from flask_wtf . csrf import generate_csrf # send CSRF token in the cookie @ app . after_request def set_csrf_cookie ( response ) : if response : response . set_cookie ( 'csrf_token' , generate_csrf ( ) ) return response
Configure an after request hook to set the csrf_token in the cookie .
81
18
24,188
def shell ( ) : ctx = _get_shell_ctx ( ) try : import IPython IPython . embed ( header = _get_shell_banner ( ) , user_ns = ctx ) except ImportError : import code code . interact ( banner = _get_shell_banner ( verbose = True ) , local = ctx )
Runs a shell in the app context . If IPython is installed it will be used otherwise the default Python shell is used .
76
26
24,189
def login ( self ) : form = self . _get_form ( 'SECURITY_LOGIN_FORM' ) if form . validate_on_submit ( ) : try : self . security_service . login_user ( form . user , form . remember . data ) except AuthenticationError as e : form . _errors = { '_error' : [ str ( e ) ] } else : self . after_this_request ( self . _commit ) if request . is_json : return self . jsonify ( { 'token' : form . user . get_auth_token ( ) , 'user' : form . user } ) self . flash ( _ ( 'flask_unchained.bundles.security:flash.login' ) , category = 'success' ) return self . redirect ( 'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT' ) else : # FIXME-identity identity_attrs = app . config . SECURITY_USER_IDENTITY_ATTRIBUTES msg = f"Invalid {', '.join(identity_attrs)} and/or password." # we just want a single top-level form error form . _errors = { '_error' : [ msg ] } for field in form . _fields . values ( ) : field . errors = None if form . errors and request . is_json : return self . jsonify ( { 'error' : form . errors . get ( '_error' ) [ 0 ] } , code = HTTPStatus . UNAUTHORIZED ) return self . render ( 'login' , login_user_form = form , * * self . security . run_ctx_processor ( 'login' ) )
View function to log a user in . Supports html and json requests .
372
14
24,190
def logout ( self ) : if current_user . is_authenticated : self . security_service . logout_user ( ) if request . is_json : return '' , HTTPStatus . NO_CONTENT self . flash ( _ ( 'flask_unchained.bundles.security:flash.logout' ) , category = 'success' ) return self . redirect ( 'SECURITY_POST_LOGOUT_REDIRECT_ENDPOINT' )
View function to log a user out . Supports html and json requests .
103
14
24,191
def register ( self ) : form = self . _get_form ( 'SECURITY_REGISTER_FORM' ) if form . validate_on_submit ( ) : user = self . security_service . user_manager . create ( * * form . to_dict ( ) ) self . security_service . register_user ( user ) return self . redirect ( 'SECURITY_POST_REGISTER_REDIRECT_ENDPOINT' ) return self . render ( 'register' , register_user_form = form , * * self . security . run_ctx_processor ( 'register' ) )
View function to register user . Supports html and json requests .
132
12
24,192
def send_confirmation_email ( self ) : form = self . _get_form ( 'SECURITY_SEND_CONFIRMATION_FORM' ) if form . validate_on_submit ( ) : self . security_service . send_email_confirmation_instructions ( form . user ) self . flash ( _ ( 'flask_unchained.bundles.security:flash.confirmation_request' , email = form . user . email ) , category = 'info' ) if request . is_json : return '' , HTTPStatus . NO_CONTENT elif form . errors and request . is_json : return self . errors ( form . errors ) return self . render ( 'send_confirmation_email' , send_confirmation_form = form , * * self . security . run_ctx_processor ( 'send_confirmation_email' ) )
View function which sends confirmation token and instructions to a user .
193
12
24,193
def confirm_email ( self , token ) : expired , invalid , user = self . security_utils_service . confirm_email_token_status ( token ) if not user or invalid : invalid = True self . flash ( _ ( 'flask_unchained.bundles.security:flash.invalid_confirmation_token' ) , category = 'error' ) already_confirmed = user is not None and user . confirmed_at is not None if expired and not already_confirmed : self . security_service . send_email_confirmation_instructions ( user ) self . flash ( _ ( 'flask_unchained.bundles.security:flash.confirmation_expired' , email = user . email , within = app . config . SECURITY_CONFIRM_EMAIL_WITHIN ) , category = 'error' ) if invalid or ( expired and not already_confirmed ) : return self . redirect ( 'SECURITY_CONFIRM_ERROR_REDIRECT_ENDPOINT' , 'security_controller.send_confirmation_email' ) if self . security_service . confirm_user ( user ) : self . after_this_request ( self . _commit ) self . flash ( _ ( 'flask_unchained.bundles.security:flash.email_confirmed' ) , category = 'success' ) else : self . flash ( _ ( 'flask_unchained.bundles.security:flash.already_confirmed' ) , category = 'info' ) if user != current_user : self . security_service . logout_user ( ) self . security_service . login_user ( user ) return self . redirect ( 'SECURITY_POST_CONFIRM_REDIRECT_ENDPOINT' , 'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT' )
View function to confirm a user s token from the confirmation email send to them . Supports html and json requests .
410
22
24,194
def forgot_password ( self ) : form = self . _get_form ( 'SECURITY_FORGOT_PASSWORD_FORM' ) if form . validate_on_submit ( ) : self . security_service . send_reset_password_instructions ( form . user ) self . flash ( _ ( 'flask_unchained.bundles.security:flash.password_reset_request' , email = form . user . email ) , category = 'info' ) if request . is_json : return '' , HTTPStatus . NO_CONTENT elif form . errors and request . is_json : return self . errors ( form . errors ) return self . render ( 'forgot_password' , forgot_password_form = form , * * self . security . run_ctx_processor ( 'forgot_password' ) )
View function to request a password recovery email with a reset token . Supports html and json requests .
185
19
24,195
def reset_password ( self , token ) : expired , invalid , user = self . security_utils_service . reset_password_token_status ( token ) if invalid : self . flash ( _ ( 'flask_unchained.bundles.security:flash.invalid_reset_password_token' ) , category = 'error' ) return self . redirect ( 'SECURITY_INVALID_RESET_TOKEN_REDIRECT' ) elif expired : self . security_service . send_reset_password_instructions ( user ) self . flash ( _ ( 'flask_unchained.bundles.security:flash.password_reset_expired' , email = user . email , within = app . config . SECURITY_RESET_PASSWORD_WITHIN ) , category = 'error' ) return self . redirect ( 'SECURITY_EXPIRED_RESET_TOKEN_REDIRECT' ) spa_redirect = app . config . SECURITY_API_RESET_PASSWORD_HTTP_GET_REDIRECT if request . method == 'GET' and spa_redirect : return self . redirect ( spa_redirect , token = token , _external = True ) form = self . _get_form ( 'SECURITY_RESET_PASSWORD_FORM' ) if form . validate_on_submit ( ) : self . security_service . reset_password ( user , form . password . data ) self . security_service . login_user ( user ) self . after_this_request ( self . _commit ) self . flash ( _ ( 'flask_unchained.bundles.security:flash.password_reset' ) , category = 'success' ) if request . is_json : return self . jsonify ( { 'token' : user . get_auth_token ( ) , 'user' : user } ) return self . redirect ( 'SECURITY_POST_RESET_REDIRECT_ENDPOINT' , 'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT' ) elif form . errors and request . is_json : return self . errors ( form . errors ) return self . render ( 'reset_password' , reset_password_form = form , reset_password_token = token , * * self . security . run_ctx_processor ( 'reset_password' ) )
View function verify a users reset password token from the email we sent to them . It also handles the form for them to set a new password . Supports html and json requests .
529
35
24,196
def change_password ( self ) : form = self . _get_form ( 'SECURITY_CHANGE_PASSWORD_FORM' ) if form . validate_on_submit ( ) : self . security_service . change_password ( current_user . _get_current_object ( ) , form . new_password . data ) self . after_this_request ( self . _commit ) self . flash ( _ ( 'flask_unchained.bundles.security:flash.password_change' ) , category = 'success' ) if request . is_json : return self . jsonify ( { 'token' : current_user . get_auth_token ( ) } ) return self . redirect ( 'SECURITY_POST_CHANGE_REDIRECT_ENDPOINT' , 'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT' ) elif form . errors and request . is_json : return self . errors ( form . errors ) return self . render ( 'change_password' , change_password_form = form , * * self . security . run_ctx_processor ( 'change_password' ) )
View function for a user to change their password . Supports html and json requests .
255
16
24,197
def _get_pwd_context ( self , app : FlaskUnchained ) -> CryptContext : pw_hash = app . config . SECURITY_PASSWORD_HASH schemes = app . config . SECURITY_PASSWORD_SCHEMES if pw_hash not in schemes : allowed = ( ', ' . join ( schemes [ : - 1 ] ) + ' and ' + schemes [ - 1 ] ) raise ValueError ( f'Invalid password hashing scheme {pw_hash}. ' f'Allowed values are {allowed}.' ) return CryptContext ( schemes = schemes , default = pw_hash , deprecated = app . config . SECURITY_DEPRECATED_PASSWORD_SCHEMES )
Get the password hashing context .
160
6
24,198
def _get_serializer ( self , app : FlaskUnchained , name : str ) -> URLSafeTimedSerializer : salt = app . config . get ( 'SECURITY_%s_SALT' % name . upper ( ) ) return URLSafeTimedSerializer ( secret_key = app . config . SECRET_KEY , salt = salt )
Get a URLSafeTimedSerializer for the given serialization context name .
81
17
24,199
def _request_loader ( self , request : Request ) -> Union [ User , AnonymousUser ] : header_key = self . token_authentication_header args_key = self . token_authentication_key token = request . args . get ( args_key , request . headers . get ( header_key , None ) ) if request . is_json : data = request . get_json ( silent = True ) or { } token = data . get ( args_key , token ) try : data = self . remember_token_serializer . loads ( token , max_age = self . token_max_age ) user = self . user_manager . get ( data [ 0 ] ) if user and self . security_utils_service . verify_hash ( data [ 1 ] , user . password ) : return user except : pass return self . login_manager . anonymous_user ( )
Attempt to load the user from the request token .
190
10