python script to read and write a path to registry - python-2.7

I have developed a python script where i have a setting window which has the options to select the paths for the installation of software.When clicked on OK button of the setting window, i want to write all the selected paths to the registry and read the same when setting window is opened again.
My code looks as below.
def OnOk(self, event):
data1=self.field1.GetValue() #path selected in setting window
aReg = ConnectRegistry(None,HKEY_LOCAL_MACHINE)
keyVal=OpenKey(aReg,r"SOFTWARE\my path to\Registry", 0,KEY_WRITE)
try:
SetValueEx(keyVal,"Log file",0,REG_SZ,data1)
except EnvironmentError:
pass
CloseKey(keyVal)
CloseKey(aReg)
I get a error like below:
Traceback (most recent call last):
File "D:\PROJECT\project.py", line 305, in OnOk
keyVal=OpenKey(aReg,r"SOFTWARE\my path to\Registry", 0,KEY_WRITE)
WindowsError: [Error 5] Access is denied
And to read from registry,the saved registry has to show up in the setting window.I tried with the below code.Though its working but not satisfied with the way i programmed it.Help me out for the better solution
key = OpenKey(HKEY_CURRENT_USER, r'Software\my path to\Registry', 0, KEY_READ)
for i in range(4):
try:
n,v,t = EnumValue(key,i)
if i==0:
self.field2.SetValue(v)
elif i==1:
self.field3.SetValue(v)
elif i==2:
self.field4.SetValue(v)
elif i==3:
self.field1.SetValue(v)
except EnvironmentError:
pass
CloseKey(key)

#Python3 version of hugo24's snippet
import winreg
REG_PATH = r"Control Panel\Mouse"
def set_reg(name, value):
try:
winreg.CreateKey(winreg.HKEY_CURRENT_USER, REG_PATH)
registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0,
winreg.KEY_WRITE)
winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
winreg.CloseKey(registry_key)
return True
except WindowsError:
return False
def get_reg(name):
try:
registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0,
winreg.KEY_READ)
value, regtype = winreg.QueryValueEx(registry_key, name)
winreg.CloseKey(registry_key)
return value
except WindowsError:
return None
#Example MouseSensitivity
#Read value
print (get_reg('MouseSensitivity'))
#Set Value 1/20 (will just write the value to reg, the changed mouse val requires a win re-log to apply*)
set_reg('MouseSensitivity', str(10))
#*For instant apply of SystemParameters like the mouse speed on-write, you can use win32gui/SPI
#http://docs.activestate.com/activepython/3.4/pywin32/win32gui__SystemParametersInfo_meth.html

Same as #Aramanethota but with pep8 and func def for easy usage.
REG_PATH = r"SOFTWARE\my_program\Settings"
def set_reg(name, value):
try:
_winreg.CreateKey(_winreg.HKEY_CURRENT_USER, REG_PATH)
registry_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, REG_PATH, 0,
_winreg.KEY_WRITE)
_winreg.SetValueEx(registry_key, name, 0, _winreg.REG_SZ, value)
_winreg.CloseKey(registry_key)
return True
except WindowsError:
return False
def get_reg(name):
try:
registry_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, REG_PATH, 0,
_winreg.KEY_READ)
value, regtype = _winreg.QueryValueEx(registry_key, name)
_winreg.CloseKey(registry_key)
return value
except WindowsError:
return None

Python script to read from registry is as follows:
try:
root_key=OpenKey(HKEY_CURRENT_USER, r'SOFTWARE\my path to\Registry', 0, KEY_READ)
[Pathname,regtype]=(QueryValueEx(root_key,"Pathname"))
CloseKey(root_key)
if (""==Pathname):
raise WindowsError
except WindowsError:
return [""]
Python script to write to the registry is:
try:
keyval=r"SOFTWARE\my path to\Registry"
if not os.path.exists("keyval"):
key = CreateKey(HKEY_CURRENT_USER,keyval)
Registrykey= OpenKey(HKEY_CURRENT_USER, r"SOFTWARE\my path to\Registry", 0,KEY_WRITE)
SetValueEx(Registrykey,"Pathname",0,REG_SZ,Pathname)
CloseKey(Registrykey)
return True
except WindowsError:
return False
Hope it helps you all.Cheers:)

Reading registry keys:
def read(path, root=HKEY_CURRENT_USER):
path, name = os.path.split(path)
with suppress(FileNotFoundError), OpenKey(root, path) as key:
return QueryValueEx(key, name)[0]
And writing:
def write(path, value, root=HKEY_CURRENT_USER):
path, name = os.path.split(path)
with OpenKey(root, path, 0, KEY_WRITE) as key:
SetValueEx(key, name, 0, REG_SZ, value)
Extended for type handling. Provide type as argument, match current type in registry or python value type.
def write(path, value, root=HKEY_CURRENT_USER, regtype=None):
path, name = os.path.split(path)
with OpenKey(root, path, 0, KEY_WRITE|KEY_READ) as key:
with suppress(FileNotFoundError):
regtype = regtype or QueryValueEx(key, name)[1]
SetValueEx(key, name, 0, regtype or REG_DWORD if isinstance(value, int) else REG_SZ, str(value) if regtype==REG_SZ else value)
NOTE: Use of contextlib.suppress() (available since python 3.4) can be replaced by try..except..pass for older versions. The context manager interface for winreg was introduced in python 2.6.

Looks like you don't have permission to edit the Registry. Incase if you are Admin, Please run this script in Elevated state.

Here is a class I wrote (python 2) which has the ability to restore state when you finish manipulating the registry. The class was not tested properly so it may contain some bugs:
import _winreg as winreg
class Registry(object):
def __init__(self, restore_state=False):
self.m_backup = {}
self.m_restore_state = restore_state
def get_key(self, hkey, subkey, access, create_if_doesnt_exist=True):
created_key = False
registry_key = None
try:
registry_key = winreg.OpenKey(hkey, subkey, 0, access)
except WindowsError:
try:
if create_if_doesnt_exist:
registry_key = winreg.CreateKey(hkey, subkey)
if registry_key not in self.m_backup:
self.m_backup[registry_key] = ({}, (hkey, subkey))
else:
registry_key = None
except WindowsError:
if registry_key:
self.close_key(registry_key)
raise Exception('Registry does not exist and could not be created.')
return registry_key
def close_key(self, registry_key):
closed = False
if registry_key:
try:
winreg.CloseKey(registry_key)
closed = True
except:
closed = False
return closed
def get_reg_value(self, hkey, subkey, name):
value = None
registry_key = self.get_key(hkey, subkey, winreg.KEY_READ, False)
if registry_key:
try:
value, _ = winreg.QueryValueEx(registry_key, name)
except WindowsError:
value = None
finally:
self.close_key(registry_key)
return value
def set_reg_value(self, hkey, subkey, name, type, value):
registry_key = self.get_key(hkey, subkey, winreg.KEY_WRITE, True)
backed_up = False
was_set = False
if registry_key:
if self.m_restore_state:
if registry_key not in self.m_backup:
self.m_backup[registry_key] = ({}, None)
existing_value = self.get_reg_value(hkey, subkey, name)
if existing_value:
self.m_backup[registry_key][0][name] = (existing_value, type, False)
else:
self.m_backup[registry_key][0][name] = (None, None, True)
backed_up = True
try:
winreg.SetValueEx(registry_key, name, 0, type, value)
was_set = True
except WindowsError:
was_set = False
finally:
if not backed_up:
self.close_key(registry_key)
return was_set
def restore_state(self):
if self.m_restore_state:
for registry_key, data in self.m_backup.iteritems():
backup_dict, key_info = data
try:
for name, backup_data in backup_dict.iteritems():
value, type, was_created = backup_data
if was_created:
print registry_key, name
winreg.DeleteValue(registry_key, name)
else:
winreg.SetValueEx(registry_key, name, 0, type, value)
if key_info:
hkey, subkey = key_info
winreg.DeleteKey(hkey, subkey)
except:
raise Exception('Could not restore value')
self.close_key(registry_key)
def __del__(self):
if self.m_restore_state:
self.restore_state()

for Creating / writing values in registry key:
from winreg import*
import winreg
keyVal = r'SOFTWARE\\python'
try:
key = OpenKey(HKEY_LOCAL_MACHINE, keyVal, 0, KEY_ALL_ACCESS)
except:
key = CreateKey(HKEY_LOCAL_MACHINE, keyVal)
SetValueEx(key, "Start Page", 0, REG_SZ, "snakes")
CloseKey(key)
If access denied - try running the command (CMd or IDE) in administrative mode
for reading value in registry-key
from winreg import*
Registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
RawKey = OpenKey(Registry, "SOFTWARE\\python")
try:
i = 0
while 1:
name, value, type = EnumValue(RawKey, i)
print("name:",name,"value:", value,"i:", i)
i += 1
except WindowsError:
print("")

My solution:
def add_key(name,pathh):
try:
keyval=r"System\my path\Register"
if not os.path.exists("keyval"):
key = winreg.CreateKey(winreg.HKEY_CURRENT_USER,keyval)
Registrykey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"System\my path\Register", 0,winreg.KEY_WRITE)
winreg.SetValueEx(Registrykey,name,1,winreg.REG_SZ,pathh)
winreg.CloseKey(Registrykey)
return True
except WindowsError:
return False

The 'winreg' module is so ...strange working module, so, I wrote a class called 'WindowsRegistry' for working with Windows registry and 'winreg' module easier. I hope it will be more usefull:
import winreg
import re
class WindowsRegistry:
"""Class WindowsRegistry is using for easy manipulating Windows registry.
Methods
-------
query_value(full_path : str)
Check value for existing.
get_value(full_path : str)
Get value's data.
set_value(full_path : str, value : str, value_type='REG_SZ' : str)
Create a new value with data or set data to an existing value.
delete_value(full_path : str)
Delete an existing value.
query_key(full_path : str)
Check key for existing.
delete_key(full_path : str)
Delete an existing key(only without subkeys).
Examples:
WindowsRegistry.set_value('HKCU/Software/Microsoft/Windows/CurrentVersion/Run', 'Program', r'"c:\Dir1\program.exe"')
WindowsRegistry.delete_value('HKEY_CURRENT_USER/Software/Microsoft/Windows/CurrentVersion/Run/Program')
"""
#staticmethod
def __parse_data(full_path):
full_path = re.sub(r'/', r'\\', full_path)
hive = re.sub(r'\\.*$', '', full_path)
if not hive:
raise ValueError('Invalid \'full_path\' param.')
if len(hive) <= 4:
if hive == 'HKLM':
hive = 'HKEY_LOCAL_MACHINE'
elif hive == 'HKCU':
hive = 'HKEY_CURRENT_USER'
elif hive == 'HKCR':
hive = 'HKEY_CLASSES_ROOT'
elif hive == 'HKU':
hive = 'HKEY_USERS'
reg_key = re.sub(r'^[A-Z_]*\\', '', full_path)
reg_key = re.sub(r'\\[^\\]+$', '', reg_key)
reg_value = re.sub(r'^.*\\', '', full_path)
return hive, reg_key, reg_value
#staticmethod
def query_value(full_path):
value_list = WindowsRegistry.__parse_data(full_path)
try:
opened_key = winreg.OpenKey(getattr(winreg, value_list[0]), value_list[1], 0, winreg.KEY_READ)
winreg.QueryValueEx(opened_key, value_list[2])
winreg.CloseKey(opened_key)
return True
except WindowsError:
return False
#staticmethod
def get_value(full_path):
value_list = WindowsRegistry.__parse_data(full_path)
try:
opened_key = winreg.OpenKey(getattr(winreg, value_list[0]), value_list[1], 0, winreg.KEY_READ)
value_of_value, value_type = winreg.QueryValueEx(opened_key, value_list[2])
winreg.CloseKey(opened_key)
return value_of_value
except WindowsError:
return None
#staticmethod
def set_value(full_path, value, value_type='REG_SZ'):
value_list = WindowsRegistry.__parse_data(full_path)
try:
winreg.CreateKey(getattr(winreg, value_list[0]), value_list[1])
opened_key = winreg.OpenKey(getattr(winreg, value_list[0]), value_list[1], 0, winreg.KEY_WRITE)
winreg.SetValueEx(opened_key, value_list[2], 0, getattr(winreg, value_type), value)
winreg.CloseKey(opened_key)
return True
except WindowsError:
return False
#staticmethod
def delete_value(full_path):
value_list = WindowsRegistry.__parse_data(full_path)
try:
opened_key = winreg.OpenKey(getattr(winreg, value_list[0]), value_list[1], 0, winreg.KEY_WRITE)
winreg.DeleteValue(opened_key, value_list[2])
winreg.CloseKey(opened_key)
return True
except WindowsError:
return False
#staticmethod
def query_key(full_path):
value_list = WindowsRegistry.__parse_data(full_path)
try:
opened_key = winreg.OpenKey(getattr(winreg, value_list[0]), value_list[1] + r'\\' + value_list[2], 0, winreg.KEY_READ)
winreg.CloseKey(opened_key)
return True
except WindowsError:
return False
#staticmethod
def delete_key(full_path):
value_list = WindowsRegistry.__parse_data(full_path)
try:
winreg.DeleteKey(getattr(winreg, value_list[0]), value_list[1] + r'\\' + value_list[2])
return True
except WindowsError:
return False

Related

Unable to mqtt_client publish inside a class

I'm trying to use Paho MQTT Client and Multiprocessing to send temperature with defined interval. However, publish command is not working inside class. I've checked self.mqtt_client inside scheduler it has the Client object.
Is there anyone that can address problem for me?
Everything inside class is working except Scheduler.
def scheduler(self, topic, interval):
if interval != 0:
while True:
if topic == "temp":
print("Temperature published " + interval) #It's working.
self.mqtt_client.publish(topic, interval , 0 , False) #There is no error/output about this line
time.sleep(int(interval))
else:
pass
Class:
class Switcher:
config = None
mqtt_client = None
mqtt_connected = False
switches = {}
stages = {}
def __init__(self, config):
self.config = config
for switch_cfg in self.config['switches']:
self.switches[switch_cfg['topic_set']] = Switch(int(switch_cfg['gpio']), switch_cfg['topic_status'], switch_cfg['initial'])
def scheduler(self, topic, interval):
if interval != 0:
while True:
if topic == "temp":
print("Temperature published " + interval) #It's working.
self.mqtt_client.publish(topic, interval , 0 , False) #There is no error/output about this line
time.sleep(int(interval))
else:
pass
def mqtt_connect(self):
if self.mqtt_broker_reachable():
self.verbose('Connecting to ' + self.config['mqtt_host'] + ':' + self.config['mqtt_port'])
self.mqtt_client = mqtt.Client(self.config['mqtt_client_id'])
if 'mqtt_user' in self.config and 'mqtt_password' in self.config:
self.mqtt_client.username_pw_set(self.config['mqtt_user'], self.config['mqtt_password'])
self.mqtt_client.on_connect = self.mqtt_on_connect
self.mqtt_client.on_disconnect = self.mqtt_on_disconnect
self.mqtt_client.on_message = self.mqtt_on_message
try:
self.mqtt_client.connect(self.config['mqtt_host'], int(self.config['mqtt_port']), 10)
for switch_cfg in self.config['switches']:
self.mqtt_client.subscribe(switch_cfg['topic_set'], 0)
self.mqtt_client.loop_forever()
except:
self.error(traceback.format_exc())
self.mqtt_client = None
else:
self.error(self.config['mqtt_host'] + ':' + self.config['mqtt_port'] + ' not reachable!')
def mqtt_on_connect(self, mqtt_client, userdata, flags, rc):
self.mqtt_connected = True
for switch_ios in self.config['switches']:
self.mqtt_client.publish(self.config['station_status'], "available", 0, False)
self.mqtt_client.publish(switch_ios['topic_status'], self.switches[switch_ios['topic_set']].get_state(), 0, False)
temp_interval = 1
temp_process = multiprocessing.Process(target=self.scheduler, args=("temp",str(temp_interval),))
temp_process.start()
self.verbose('...mqtt_connected!')
def mqtt_broker_reachable(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
try:
s.connect((self.config['mqtt_host'], int(self.config['mqtt_port'])))
s.close()
return True
except socket.error:
return False
def start(self):
self.mqtt_connect()
You mqtt_connect function will never return.
self.mqtt_client.loop_forever() Will block until self.mqtt_client.disconnect() is called.
You should probably be using self.mqtt_client.loop_start() which will run the client loop on it's own thread in the background. You can call self.mqtt_client.loop_stop() when you want to shut the client down.

unable to write test for django model containing custom model field

I have a model for users where in the field for password is a custom field. This model works fine but i'm not able to run tests for the model.
my model
from core_engine.CustomModelFields import *
class Users(models.Model):
username = models.EmailField(unique=True)
name = models.CharField(max_length=100)
password = EncryptedField(max_length=500)
in my core_engine.CustomModelFields.py file
from account_engine.crypto import *
class EncryptedField(CharField):
def from_db_value(self, value, expression, connection, context):
value = Password.decrypt(str(value))
return value.decode("utf-8")
def to_python(self, value):
if not value:
return None
return value
#Only need to decrypt if password already encrypted.
try:
if Password.encrypt(Password.decrypt(value)) == value:
value = Password.decrypt(str(value))
return value.decode("utf-8")
except:
return value
def get_db_prep_save(self, value, connection):
value = Password.encrypt(str(value))
return value
and finally in accounts_engine.crypto.py file i have
import base64, hashlib
from django.db import models
from Crypto import Random
from Crypto.Cipher import AES
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-s[-1]]
class Password(models.Model):
def encrypt( raw ):
mysecretpassword = 'somepassword'
KEY = hashlib.sha256(mysecretpassword.encode('utf-8')).digest()
raw = pad(raw)
iv = Random.new().read( AES.block_size )
cipher = AES.new( KEY, AES.MODE_CBC, iv )
return base64.b64encode( iv + cipher.encrypt( raw ) )
def decrypt( enc ):
mysecretpassword = 'somepassword'
KEY = hashlib.sha256(mysecretpassword.encode('utf-8')).digest()
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(KEY, AES.MODE_CBC, iv )
return unpad(cipher.decrypt( enc[16:] ))
All i want to do is just test my Users model and see that i'm able to create a user during test, which will be required for other tests
so in my test.py file i have
class UsersTestCase(TestCase):
#classmethod
def setUp(self):
print(dt.datetime.now())
self.user= Users.objects.create(
username = 'test#test.com',
date_first_registered = dt.datetime.now(),
password = Password.encrypt('abc')
)
def test_get_user(self):
first_customer = Users.objects.first()
self.assertEqual(first_customer.username, 'test#test.com')
On running the above test, i get an error stating :
TypeError: Object type <class 'str'> cannot be passed to C code
Edit : i understand that the error is due to me passing the password as Password.encrypt('abc').
what changes should i make to my test function in order to create to create a new user
TRACEBACK
Traceback (most recent call last):
File "D:\project_path\account_engine\tests\tests_models.py", line 15, in setUp
password = Password.encrypt('abc')
File "D:\project_path\account_engine\crypto.py", line 21, in encrypt
return base64.b64encode( iv + cipher.encrypt( raw ) )
File "d:\project_path\venv\lib\site-packages\Crypto\Cipher\_mode_cbc.py", line 178, in encrypt
c_uint8_ptr(plaintext),
File "d:\project_path\venv\lib\site-packages\Crypto\Util\_raw_api.py", line 144, in c_uint8_ptr
raise TypeError("Object type %s cannot be passed to C code" % type(data))
TypeError: Object type <class 'str'> cannot be passed to C code
Encrypt method accepts bytes string type and not str in Python 3:
Plaintexts and ciphertexts (input/output) can only be bytes, bytearray or memoryview. In Python 3, you cannot pass strings. In Python 2, you cannot pass Unicode strings.
You need to encode raw first:
def encrypt( raw ):
mysecretpassword = 'somepassword'
KEY = hashlib.sha256(mysecretpassword.encode('utf-8')).digest()
raw = pad(raw)
iv = Random.new().read( AES.block_size )
cipher = AES.new( KEY, AES.MODE_CBC, iv )
return base64.b64encode(iv + cipher.encrypt(raw.encode('utf-8')))

Replacement for django `render_options`

So I am implementing this answer: Country/State/City dropdown menus inside the Django admin inline, but the def render piece of code needs to be redone.... I have managed to redo it, but I am struggling to find a replacement (or the correct code) for the self.render_options method (which was deprecated on 1.11) of the Widget class.
I am on Django 2.1.
What should I change?
Here is my code:
class StateChoiceWidget(widgets.Select):
def render(self, name, value, attrs=None, renderer=None):
self.choices = [(u"", u"---------")]
if value is None:
value = ''
model_obj = self.form_instance.instance
if model_obj and model_obj.country:
for m in model_obj.country.state_set.all():
self.choices.append((m.id, smart_text(m)))
else:
obj = State.objects.get(id=value)
for m in State.objects.filter(country=obj.country):
self.choices.append((m.id, smart_text(m)))
final_attrs = self.build_attrs(attrs)
output = ['<select%s>' % flatatt(final_attrs)]
for option in self.choices:
output.append('<option value="%s">%s</option>' % (option[0], option[1]))
output.append('</select>')
return mark_safe(''.join(output))
Original poster updated the sample code, so now it doesn't show the code in the question: see previous revision https://stackoverflow.com/revisions/52174508/1
So I figured out the answer. Will post it here in case someone runs into the same issue.
class StateChoiceWidget(widgets.Select):
def render(self, name, value, attrs=None, renderer=None):
self.choices = [(u"", u"---------")]
if value is None or value == '':
value = ''
model_obj = self.form_instance.instance
if model_obj and model_obj.country:
for m in model_obj.country.state_set.all():
self.choices.append((m.id, smart_text(m)))
else:
obj = State.objects.get(id=value)
for m in State.objects.filter(country=obj.country):
self.choices.append((m.id, smart_text(m)))
final_attrs = self.build_attrs(attrs)
s = widgets.Select(choices=self.choices)
select_html = s.render(name=name,value=value,attrs=attrs)
return mark_safe(''.join(select_html))

Replace string before brace in Python-script

I modified jtaubers python script to convert betababel-code to the original greek letters. After some modifications (and help!) I got the script to run.
# beta2unicode.py
#
# Version 2004-11-23
#
# James Tauber
# http://jtauber.com/
#
# You are free to redistribute this, but please inform me of any errors
#
# USAGE:
#
# trie = beta2unicodeTrie()
# beta = "LO/GOS\n";
# unicode, remainder = trie.convert(beta)
#
# - to get final sigma, string must end in \n
# - remainder will contain rest of beta if not all can be converted
class Trie:
def __init__(self):
self.root = [None, {}]
def add(self, key, value):
curr_node = self.root
for ch in key:
curr_node = curr_node[1].setdefault(ch, [None, {}])
curr_node[0] = value
def find(self, key):
curr_node = self.root
for ch in key:
try:
curr_node = curr_node[1][ch]
except KeyError:
return None
return curr_node[0]
def findp(self, key):
curr_node = self.root
remainder = key
for ch in key:
try:
curr_node = curr_node[1][ch]
except KeyError:
return (curr_node[0], remainder)
remainder = remainder[1:]
return (curr_node[0], remainder)
def convert(self, keystring):
valuestring = ""
key = keystring
while key:
value, key = self.findp(key)
if not value:
return (valuestring, key)
valuestring += value
return (valuestring, key)
def beta2unicodeTrie():
t = Trie()
t.add("*A", u"\u0391")
t.add("*B", u"\u0392")
t.add("*G", u"\u0393")
t.add("*D", u"\u0394")
t.add("*E", u"\u0395")
t.add("*Z", u"\u0396")
t.add("*H", u"\u0397")
t.add("*Q", u"\u0398")
t.add("*I", u"\u0399")
t.add("*K", u"\u039A")
t.add("*L", u"\u039B")
t.add("*M", u"\u039C")
t.add("*N", u"\u039D")
t.add("*C", u"\u039E")
t.add("*O", u"\u039F")
t.add("*P", u"\u03A0")
t.add("*R", u"\u03A1")
t.add("*S", u"\u03A3")
t.add("*T", u"\u03A4")
t.add("*U", u"\u03A5")
t.add("*F", u"\u03A6")
t.add("*X", u"\u03A7")
t.add("*Y", u"\u03A8")
t.add("*W", u"\u03A9")
t.add("A", u"\u03B1")
t.add("B", u"\u03B2")
t.add("G", u"\u03B3")
t.add("D", u"\u03B4")
t.add("E", u"\u03B5")
t.add("Z", u"\u03B6")
t.add("H", u"\u03B7")
t.add("Q", u"\u03B8")
t.add("I", u"\u03B9")
t.add("K", u"\u03BA")
t.add("L", u"\u03BB")
t.add("M", u"\u03BC")
t.add("N", u"\u03BD")
t.add("C", u"\u03BE")
t.add("O", u"\u03BF")
t.add("P", u"\u03C0")
t.add("R", u"\u03C1")
t.add("S\n", u"\u03C2")
t.add("S,", u"\u03C2,")
t.add("S.", u"\u03C2.")
t.add("S:", u"\u03C2:")
t.add("S}", u"\u03C2:")
t.add("S;", u"\u03C2;")
t.add("S]", u"\u03C2]")
t.add("S#", u"\u03C2#")
t.add("S_", u"\u03C2_")
t.add("S", u"\u03C3")
t.add("T", u"\u03C4")
t.add("U", u"\u03C5")
t.add("F", u"\u03C6")
t.add("X", u"\u03C7")
t.add("Y", u"\u03C8")
t.add("W", u"\u03C9")
t.add("I+", U"\u03CA")
t.add("U+", U"\u03CB")
t.add("A)", u"\u1F00")
t.add("A(", u"\u1F01")
t.add("A)\\", u"\u1F02")
t.add("A(\\", u"\u1F03")
t.add("A)!", u"\u1F02")
t.add("A(!", u"\u1F03")
t.add("A)/", u"\u1F04")
t.add("A(/", u"\u1F05")
t.add("E)", u"\u1F10")
t.add("E(", u"\u1F11")
t.add("E)\\", u"\u1F12")
t.add("E(\\", u"\u1F13")
t.add("E)!", u"\u1F12")
t.add("E(!", u"\u1F13")
t.add("E)/", u"\u1F14")
t.add("E(/", u"\u1F15")
t.add("H)", u"\u1F20")
t.add("H(", u"\u1F21")
t.add("H)\\", u"\u1F22")
t.add("H(\\", u"\u1F23")
t.add("H)!", u"\u1F22")
t.add("H(!", u"\u1F23")
t.add("H)/", u"\u1F24")
t.add("H(/", u"\u1F25")
t.add("I)", u"\u1F30")
t.add("I(", u"\u1F31")
t.add("I)\\", u"\u1F32")
t.add("I(\\", u"\u1F33")
t.add("I)!", u"\u1F32")
t.add("I(!", u"\u1F33")
t.add("I)/", u"\u1F34")
t.add("I(/", u"\u1F35")
t.add("O)", u"\u1F40")
t.add("O(", u"\u1F41")
t.add("O)\\", u"\u1F42")
t.add("O(\\", u"\u1F43")
t.add("O)!", u"\u1F42")
t.add("O(!", u"\u1F43")
t.add("O)/", u"\u1F44")
t.add("O(/", u"\u1F45")
t.add("U)", u"\u1F50")
t.add("U(", u"\u1F51")
t.add("U)\\", u"\u1F52")
t.add("U(\\", u"\u1F53")
t.add("U)!", u"\u1F52")
t.add("U(!", u"\u1F53")
t.add("U)/", u"\u1F54")
t.add("U(/", u"\u1F55")
t.add("W)", u"\u1F60")
t.add("W(", u"\u1F61")
t.add("W)\\", u"\u1F62")
t.add("W(\\", u"\u1F63")
t.add("W)!", u"\u1F62")
t.add("W(!", u"\u1F63")
t.add("W)/", u"\u1F64")
t.add("W(/", u"\u1F65")
t.add("A)=", u"\u1F06")
t.add("A(=", u"\u1F07")
t.add("H)=", u"\u1F26")
t.add("H(=", u"\u1F27")
t.add("I)=", u"\u1F36")
t.add("I(=", u"\u1F37")
t.add("U)=", u"\u1F56")
t.add("U(=", u"\u1F57")
t.add("W)=", u"\u1F66")
t.add("W(=", u"\u1F67")
t.add("*A)", u"\u1F08")
t.add("*)A", u"\u1F08")
t.add("*A(", u"\u1F09")
t.add("*(A", u"\u1F09")
#
t.add("*(\A", u"\u1F0B")
t.add("*A)/", u"\u1F0C")
t.add("*)/A", u"\u1F0C")
t.add("*A(/", u"\u1F0F")
t.add("*(/A", u"\u1F0F")
t.add("*E)", u"\u1F18")
t.add("*)E", u"\u1F18")
t.add("*E(", u"\u1F19")
t.add("*(E", u"\u1F19")
#
t.add("*(\E", u"\u1F1B")
t.add("*E)/", u"\u1F1C")
t.add("*)/E", u"\u1F1C")
t.add("*E(/", u"\u1F1D")
t.add("*(/E", u"\u1F1D")
t.add("*H)", u"\u1F28")
t.add("*)H", u"\u1F28")
t.add("*H(", u"\u1F29")
t.add("*(H", u"\u1F29")
t.add("*H)\\", u"\u1F2A")
t.add(")\\*H", u"\u1F2A")
t.add("*)\\H", u"\u1F2A")
t.add("*H)!", u"\u1F2A")
t.add(")!*H", u"\u1F2A")
t.add("*)!H", u"\u1F2A")
#
t.add("*H)/", u"\u1F2C")
t.add("*)/H", u"\u1F2C")
#
t.add("*)=H", u"\u1F2E")
t.add("(/*H", u"\u1F2F")
t.add("*(/H", u"\u1F2F")
t.add("*I)", u"\u1F38")
t.add("*)I", u"\u1F38")
t.add("*I(", u"\u1F39")
t.add("*(I", u"\u1F39")
#
#
t.add("*I)/", u"\u1F3C")
t.add("*)/I", u"\u1F3C")
#
#
t.add("*I(/", u"\u1F3F")
t.add("*(/I", u"\u1F3F")
#
t.add("*O)", u"\u1F48")
t.add("*)O", u"\u1F48")
t.add("*O(", u"\u1F49")
t.add("*(O", u"\u1F49")
#
#
t.add("*(\O", u"\u1F4B")
t.add("*O)/", u"\u1F4C")
t.add("*)/O", u"\u1F4C")
t.add("*O(/", u"\u1F4F")
t.add("*(/O", u"\u1F4F")
#
t.add("*U(", u"\u1F59")
t.add("*(U", u"\u1F59")
#
t.add("*(/U", u"\u1F5D")
#
t.add("*(=U", u"\u1F5F")
t.add("*W)", u"\u1F68")
t.add("*W(", u"\u1F69")
t.add("*(W", u"\u1F69")
#
#
t.add("*W)/", u"\u1F6C")
t.add("*)/W", u"\u1F6C")
t.add("*W(/", u"\u1F6F")
t.add("*(/W", u"\u1F6F")
t.add("*A)=", u"\u1F0E")
t.add("*)=A", u"\u1F0E")
t.add("*A(=", u"\u1F0F")
t.add("*W)=", u"\u1F6E")
t.add("*)=W", u"\u1F6E")
t.add("*W(=", u"\u1F6F")
t.add("*(=W", u"\u1F6F")
t.add("A\\", u"\u1F70")
t.add("A!", u"\u1F70")
t.add("A/", u"\u1F71")
t.add("E\\", u"\u1F72")
t.add("E!", u"\u1F72")
t.add("E/", u"\u1F73")
t.add("H\\", u"\u1F74")
t.add("H!", u"\u1F74")
t.add("H/", u"\u1F75")
t.add("I\\", u"\u1F76")
t.add("I!", u"\u1F76")
t.add("I/", u"\u1F77")
t.add("O\\", u"\u1F78")
t.add("O!", u"\u1F78")
t.add("O/", u"\u1F79")
t.add("U\\", u"\u1F7A")
t.add("U!", u"\u1F7A")
t.add("U/", u"\u1F7B")
t.add("W\\", u"\u1F7C")
t.add("W!", u"\u1F7C")
t.add("W/", u"\u1F7D")
t.add("A)/|", u"\u1F84")
t.add("A(/|", u"\u1F85")
t.add("H)|", u"\u1F90")
t.add("H(|", u"\u1F91")
t.add("H)/|", u"\u1F94")
t.add("H)=|", u"\u1F96")
t.add("H(=|", u"\u1F97")
t.add("W)|", u"\u1FA0")
t.add("W(=|", u"\u1FA7")
t.add("A=", u"\u1FB6")
t.add("H=", u"\u1FC6")
t.add("I=", u"\u1FD6")
t.add("U=", u"\u1FE6")
t.add("W=", u"\u1FF6")
t.add("I\\+", u"\u1FD2")
t.add("I!+", u"\u1FD2")
t.add("I/+", u"\u1FD3")
t.add("I+/", u"\u1FD3")
t.add("U\\+", u"\u1FE2")
t.add("U!+", u"\u1FE2")
t.add("U/+", u"\u1FE3")
t.add("A|", u"\u1FB3")
t.add("A/|", u"\u1FB4")
t.add("H|", u"\u1FC3")
t.add("H/|", u"\u1FC4")
t.add("W|", u"\u1FF3")
t.add("W|/", u"\u1FF4")
t.add("W/|", u"\u1FF4")
t.add("A=|", u"\u1FB7")
t.add("H=|", u"\u1FC7")
t.add("W=|", u"\u1FF7")
t.add("R(", u"\u1FE4")
t.add("*R(", u"\u1FEC")
t.add("*(R", u"\u1FEC")
# t.add("~", u"~")
# t.add("-", u"-")
# t.add("(null)", u"(null)")
# t.add("&", "&")
t.add("0", u"0")
t.add("1", u"1")
t.add("2", u"2")
t.add("3", u"3")
t.add("4", u"4")
t.add("5", u"5")
t.add("6", u"6")
t.add("7", u"7")
t.add("8", u"8")
t.add("9", u"9")
t.add("#", u"#")
t.add("$", u"$")
t.add(" ", u" ")
t.add(".", u".")
t.add(",", u",")
t.add("'", u"'")
t.add(":", u":")
t.add(";", u";")
t.add("_", u"_")
t.add("[", u"[")
t.add("]", u"]")
t.add("\n", u"")
return t
import sys
t = beta2unicodeTrie()
import re
BCODE = re.compile(r'\\bcode{[^}]*}')
for line in open(sys.argv[1]):
matches = BCODE.search(line)
for match in BCODE.findall(line):
bcode = match[7:-1]
a, b = t.convert(bcode.upper())
if b:
raise IOError("failed conversion '%s' in '%s'" % (b, line))
converted = a.encode("utf-8")
line = line.replace(match, converted)
print(line.rstrip())
There is one thing left though. The final sigma "ς" gets not converted like this when it stands at the end of the \bcode{}-Makro. For example here:
\bcode{ei)=dos}
The script converts it to the normal sigma "σ" Unicode: U+03C3
How do I make the script recognize to convert the "s" when it stands right before the end-brace to the Unicode U+03C2?
This:
t.add("S}", u"\u03C2}")
does not do the trick

flask + wtforms nameerror

flask + wtforms
Hello, I have some problems with the transfer of data into a form
def edit_comment(n):
idlist = str(n)
if (r.exists('entries:%s' %idlist) != True):
return abort(404)
if 'user_id' not in session:
return abort(401)
if (g.user['group_access'] == '1'):
return abort(403)
form = EditForm(idlist)
return render_template('edit_comment.html',idlist = idlist, r = r, form = form)
...
class EditForm(Form):
edit_title = TextField("Title",validators = [Required()] ,default =r.hget('entries:%s' %idlist, 'title'))
edit_text = TextAreaField("Text",validators = [Required()],default =r.hget('entries:%s' %idlist, 'text'))
...
Traceback (most recent call last):
File "run.py", line 129, in <module>
class EditForm(Form):
File "run.py", line 130, in EditForm
edit_title = TextField("Title",validators = [Required()] ,default =r.hget('entries:%s' %idlist, 'title'))
NameError: name 'idlist' is not defined
here there are clear problems with data transmission. tried to pass through the constructor, but so far No results
You need to set the default value on the EditForm instance. Right now it' set at import time - clearly not what you want, even if the variable was defined. Actually, you don't even need the default field for it - just set it directly:
form = EditForm()
form.edit_title.data = r.hget('entries:%s' % idlist, 'title')
form.edit_text.data = r.hget('entries:%s' % idlist, 'text')
return render_template('edit_comment.html', idlist=idlist, r=r, form=form)
Note: Usually it's a good idea to have your view function to have a structure similar to this:
form = EditForm()
if form.validate_on_submit():
# do whatever should be done on submit, then redirect somewhere
return redirect(...)
elif request.method == 'GET':
# Populate the form with initial values
form.edit_title.data = ...
form.edit_text.data = ...
return render_template(..., form=form)
That way whatever the user entered is preserved in case the validation fails, but if he opens the form for the first time it's populated with whatever default data (e.g. the current values from your db) you want.