def post(self):
update = self.request.get('update')
if users.get_current_user():
if update:
personal = db.GqlQuery("SELECT * FROM Personal WHERE __key__ = :1", db.Key(update))
personal.name = self.request.get('name')
personal.gender = self.request.get('gender')
personal.mobile_num = self.request.get('mobile_num')
personal.birthdate = int(self.request.get('birthdate'))
personal.birthplace = self.request.get('birthplace')
personal.address = self.request.get('address')
personal.geo_pos = self.request.get('geo_pos')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.put()
self.redirect('/admin/personal')
else:
personal= Personal()
personal.name = self.request.get('name')
personal.gender = self.request.get('gender')
personal.mobile_num = self.request.get('mobile_num')
personal.birthdate = int(self.request.get('birthdate'))
personal.birthplace = self.request.get('birthplace')
personal.address = self.request.get('address')
personal.geo_pos = self.request.get('geo_pos')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.put()
self.redirect('/admin/personal')
else:
self.response.out.write('I\'m sorry, you don\'t have permission to add this LP Personal Data.')
Should this will update the existing record if the 'update' is querystring containing key datastore key. I try this but keep adding new record/entity. Please give me some sugesstion to correctly updating the record/entity.
Correction? :
def post(self):
update = self.request.get('update')
if users.get_current_user():
if update:
personal = Personal.get(db.Key(update))
personal.name = self.request.get('name')
personal.gender = self.request.get('gender')
personal.mobile_num = self.request.get('mobile_num')
personal.birthdate = int(self.request.get('birthdate'))
personal.birthplace = self.request.get('birthplace')
personal.address = self.request.get('address')
personal.geo_pos = self.request.get('geo_pos')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.put()
self.redirect('/admin/personal')
else:
personal= Personal()
personal.name = self.request.get('name')
personal.gender = self.request.get('gender')
personal.mobile_num = self.request.get('mobile_num')
personal.birthdate = int(self.request.get('birthdate'))
personal.birthplace = self.request.get('birthplace')
personal.address = self.request.get('address')
personal.geo_pos = self.request.get('geo_pos')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.put()
self.redirect('/admin/personal')
else:
self.response.out.write('I\'m sorry, you don\'t have permission to add this LP Personal Data.')
There's no need to do a query when you know the key: Simply call db.get() on the key to retrieve it directly, which is much faster than doing a query.
As to why you're creating a new record each time, it looks like you're not passing in 'update' to your page correctly. Try logging the query string parameters to see what's going wrong.
I finally answer this myself, Thanks for Nick Johnson guide on this.
I cannot get the query string url as 'string key' that always raise BadKeyError: Invalid string key exception.
I try to put this 'update' string as hidden field on html edit form and this works since 'update' is a valid 'string key' now.
def post(self):
update = self.request.get('update')
if users.get_current_user():
if update != '':
personal = Personal.get(db.Key(update))
Related
I have no clue what I did wrong as it was working completely fine earlier, I haven't changed anything within the code but the error 'TypeError("'AssetId' is an invalid keyword argument for Assets")' keeps popping up? My goal is to basically successfully add an asset. please help!
#route('/newasset', method = 'post')
def newasset():
db_engine = create_engine('sqlite:///db/MusicAssets.db')
#dynamic class creation - creates a sessionmaker class
Session = sessionmaker(bind=db_engine)
session = Session()
new_assetid = request.forms.get('AssetId')
new_assetname = request.forms.get('AssetName')
new_category = request.forms.get('Category')
new_status= request.forms.get('Status')
new_borrower = request.forms.get('Borrower')
new_value = request.forms.get('Value')
new_asset = Assets(
AssetId = new_assetid,
AssetName = new_assetname,
Category = new_category,
Status = new_status,
Borrower = new_borrower,
Value = new_value
)
session.add(new_asset)
session.commit()
return template('success.tpl', message = 'Asset added')
Hi and thanks in advance for your help. I am not a Python expert but an accomplished programmer in other languages.
I'm getting the error on "is_server_running"
Client
from ibw.client import IBClient
REGULAR_USERNAME = 'MY_ACCOUNT_USERNAME'
REGULAR_ACCOUNT = 'MY_ACCOUNT_NUMBER'
# Create a new session of the IB Web API.
ib_client = IBClient(username=REGULAR_USERNAME,
account=REGULAR_ACCOUNT,
client_gateway_path=None,
is_server_running=True)
class IBClient():
def __init__(self, username: str, account: str, client_gateway_path: str = None, is_server_running:
bool = True) -> None
self.account = account
self.username = username
self.client_gateway_path = client_gateway_path
self.client_portal_client = ClientPortal()
self.api_version = 'v1/'
self._operating_system = sys.platform
self.session_state_path: pathlib.Path =
pathlib.Path(__file__).parent.joinpath('server_session.json').resolve()
self.authenticated = False
self._is_server_running = is_server_running
# Define URL Components
ib_gateway_host = r"https://localhost"
ib_gateway_port = r"5000"
self.ib_gateway_path = ib_gateway_host + ":" + ib_gateway_port
self.backup_gateway_path = r"https://cdcdyn.interactivebrokers.com/portal.proxy"
self.login_gateway_path = self.ib_gateway_path + "/sso/Login?forwardTo=22&RL=1&ip2loc=on"
[more code]
Again thanks in advance for your help
Bob
I'm quite new to python and I'm trying to put together a little app with npyscreen. Part of this app has a page with a FormControlBox, that reveals a FormControlBox when selected. This second FormControlBox, when selected, reveals some text fields.
The issue I'm having is getting the second FormControlBox to change its value to False if the first one is unselected (making the second hidden). Here is the approach I'm attempting to take in this form class.
class envMenuForm(npyscreen.Form):
def afterEditing(self):
# Updating mapping with values set from form creation
hostConfig["hostname"] = self.hostname.value
hostConfig["domain"] = self.domain.value
hostConfig["fqdn"] = self.fqdn.value
self.parentApp.setNextForm('CEV')
def create(self):
# Defining vars from current baseConfig mapping from JSON file
self.hostname = hostConfig["hostname"]
self.domain = hostConfig["domain"]
self.fqdn = hostConfig["fqdn"]
# Adding text fields with the defaults from the config file
self.hostname = self.add(npyscreen.TitleText, name = "System Hostname:", value = self.hostname)
self.domain = self.add(npyscreen.TitleText, name = "System Domain:", value = self.domain)
self.fqdn = self.add(npyscreen.TitleText, name = "System Fully Qualified Domain Name:", value = self.fqdn)
self.et0status = self.add(npyscreen.FormControlCheckbox, name="Enable Eth0", value = False)
self.et0type = self.add(npyscreen.FormControlCheckbox, name = "Configure as Static Address (ignore for DHCP)", value = False)
self.et0ipaddress = self.add(npyscreen.TitleText, name = "IP Address", value = "127.0.0.1")
self.et0status.addVisibleWhenSelected(self.et0type)
self.et0type.addVisibleWhenSelected(self.et0ipaddress)
def while_editing(self,arg):
if arg is self.et0type:
if arg.hidden:
self.et0type.value = False
After a bunch of refactoring I was able to solve this utilizing the adjust_widgets() with some background logic to ensure it doesn't fire off too much.
I am having issues with my below API request to Flickr. My function takes as input a list of 10 photo ids. However when I print the data from my function I am only getting information based on 1 photo ID. Looking at my below function any ideas on what may be causing the contents of only 1 photo ID to print? Any help would be great.
for item in get_flickr_data(word)["photos"]["photo"]:
photo_ids =item["id"].encode('utf-8')
lst_photo_ids.append(photo_ids)
print lst_photo_ids
lst_photo_ids = ['34117701526', '33347528313', '34158745075', '33315997274', '33315996984', '34028007021', '33315995844', '33347512113', '33315784134', '34024299271']
def get_photo_data(lst_photo_ids):
baseurl = "https://api.flickr.com/services/rest/"
params_d = {}
params_d["method"] = "flickr.photos.getInfo"
params_d["format"] = "json"
params_d["photo_id"] = photo_ids
params_d["api_key"] = FLICKR_KEY
unique_identifier = params_unique_combination(baseurl,params_d)
if unique_identifier in CACHE_DICTION:
flickr_data_diction = CACHE_DICTION[unique_identifier]
else:
resp = requests.get(baseurl,params_d)
json_result_text = resp.text[14:-1]
flickr_data_diction = json.loads(json_result_text)
CACHE_DICTION[unique_identifier] = flickr_data_diction
fileref = open(CACHE_FNAME,"w")
fileref.write(json.dumps(CACHE_DICTION))
fileref.close()
return flickr_data_diction
print get_photo_data(photo_ids)
I know this topic is talked many times in Stackoverflow but it concerns many different methods and I need help. I'm stuck since four hours ^^'
Here is the message : local variable 'menuItem' referenced before assignment
def B2BpartnerMenuDetailModify(request, partnerId, menuId, menuItemId):
message = ''
e = B2BpartnerUser(request, partnerId)
try:
menuDetail = Menu.objects.get(id=menuId)
except Menu.DoesNotExist:
return logoutUser(request)
if request.method == 'POST':
form = MenuDetailForm(request.POST, mySelf=partnerId)
if form.is_valid():
descrShort = form.cleaned_data['descrShort']
paragraph = form.cleaned_data['paragraph']
producteur = form.cleaned_data['producteur']
position = MenuItem.objects.filter(menuId = menuDetail).filter(paragraph = paragraph).count() + 1
menuItem = MenuItem(menuId = menuDetail)
menuItem.descrShort = descrShort
menuItem.paragraph = paragraph
menuItem.producteur = producteur
menuItem.save()
if producteur > 0:
menuItemProd = MenuItemProd(menuItemId = menuItem)
menuItemProd.entrepriseId = producteur
menuItemProd.save()
message = _('Details modified successfuly')
else:
data = {'descrShort': menuItem.descrShort, 'paragraph': menuItem.paragraph, 'producteur': menuItem.producteur}
form = MenuDetailForm(initial=data)
menuItems = MenuItem.objects.filter(menuId = menuDetail).select_related()
menus = Menu.objects.filter(entrepriseId=e)
menuParagraph = MenuParagraph.objects.filter(actif=1)
modifier = True
#detail = False
return render (request, 'front/B2Bmenu.html', {'MenuDetailForm': form, 'menus': menus, 'message': message, 'partnerId': partnerId, 'modifier': modifier, 'detail': detail, 'menuDetail': menuDetail, 'menuParagraph': menuParagraph, 'menuId': menuId, 'menuItems': menuItems})
I'm sure I can get my page when this error is resolved. I'm sure it's a little error, I'm a beginner at Python but I love the language :)
If you want I can give you more details but I don't think it's necessary ^^
Have a nice day and thank you for your help :)
I found it !
I just forgot to add another try for this variable, just after the first try.
try:
menuItem = MenuItem.objects.get(id=menuItemId)
except MenuItem.DoesNotExist:
return logoutUser(request)