Python PyInquirer - action after input - python

I would like to have an action after given certain output from PyInquirer. The idea is to have a menu to select certain items. When choosing a item, it should launch a script or another action. In this example i've used print("okay") as a example.
from __future__ import print_function, unicode_literals
from PyInquirer import style_from_dict, Token, prompt, Separator
from pprint import pprint
import os
style = style_from_dict({
Token.Separator: '#cc5454',
Token.QuestionMark: '#673ab7 bold',
Token.Selected: '#cc5454', # default
Token.Pointer: '#673ab7 bold',
Token.Instruction: '', # default
Token.Answer: '#f44336 bold',
Token.Question: '',
})
questions = [
{
'type': 'checkbox',
'message': 'Select a VIP build',
'name': 'F5 configuration build',
'choices': [
Separator('= VIPS ='),
{
'name': 'Nieuwe HTTP VIP'
},
{
'name': 'Nieuwe HTTPS VIP'
},
{
'name': 'Niewe VIP'
},
Separator('= Pools ='),
{
'name': 'Nieuwe Pool'
},
{
'name': 'Bestaande pool'
},
Separator('= Pool member ='),
{
'name': 'Nieuwe Pool Members'
},
{
'name': 'Bestaande Pool Members'
},
],
'validate': lambda answer: 'You must choose atleast one option.' \
if len(answer) == 0 else True
}
]
answers = prompt(questions, style=style)
pprint(answers)
if answers == ("{'F5 configuration build': ['Nieuwe HTTP VIP']}"):
print("okay")
So the
if answers == ("{'F5 configuration build': ['Nieuwe HTTP VIP']}"):
print("okay")
Should print okay after choosing the first choice, but it doesn't happend.
Any advice would be welcome!
Edit Spelling

The name should be a value that is easier to evaluate, for example only "F5" the user will not see it.
It is a type of dict data, you must access it through the index.
answers = prompt(questions, style=style)
pprint(answers)
if answers.get('F5', []) == ['Nieuwe HTTP VIP']:
print("okay")

Related

Error in creation of work-item in Azure DevOps using Pytest/Python

I am trying to create a work-item using Python and requests library.
def test_create_work_item(work_items):
payload = {
'op': 'add',
'path': '/fields/System.Title',
'value': 'Sample bug'
}
pl = json.dumps(payload)
work_item = work_items.create(body=pl, type='bug')
assert work_item.status_code == 200
I am getting the below error for this :
{"$id":"1","innerException":null,"message":"You must pass a valid patch document in the body of the request.","typeName":"Microsoft.VisualStudio.Services.Common.VssPropertyValidationException,Microsoft.VisualStudio.Services.Common","typeKey":"VssPropertyValidationException","errorCode":0,"eventId":3000}
The same body works okay with Postman. So not sure what more is needed here to get it working.
I`m not familiar with Python.... Check this example: Create work item
The API uses an array of new fields:
[
{
"op": "add",
"path": "/fields/System.Title",
"from": null,
"value": "Sample task"
}
]
In your case, you use just one field in the request:
{
'op': 'add',
'path': '/fields/System.Title',
'value': 'Sample bug'
}

How to parse text output separated with space

First lines are field names. Others are values but if no corresponding data, values are filled with spaces.
In particular, bindings has no values in SHORTNAMES and APIGROUP.
pods has no value in APIGROUP
$ kubectl api-resources
NAME SHORTNAMES APIGROUP NAMESPACED KIND
bindings true Binding
pods po true Pod
deployments deploy apps true Deployment
Finally, I would like to treat output data as python dict, which key is field name.
First of all, it seems to replace spaced no value with the dummy value by regex.
NAME SHORTNAMES APIGROUP NAMESPACED KIND
bindings no-value no-value true Binding
Is it possibe?
Here is a solution with regex.
import re
data = """NAME SHORTNAMES APIGROUP NAMESPACED KIND
bindings true Binding
pods po true Pod
deployments deploy apps true Deployment"""
regex = re.compile(
"(?P<name>\S+)\s+"
"(?P<shortname>\S+)\s+"
"(?P<group>\S+)\s+"
"(?P<namespace>\S+)\s+"
"(?P<kind>\S+)"
)
header = data.splitlines()[0]
for match in regex.finditer(header):
name_index = match.start('name')
shortname_index = match.start('shortname')
group_index = match.start('group')
namespace_index = match.start('namespace')
kind_index = match.start('kind')
def get_text(line, index):
result = ''
for char in line[index:]:
if char == ' ':
break
result += char
if result:
return result
else:
return "no-value"
resources = []
for line in data.splitlines()[1:]:
resources.append({
"name" : get_text(line, name_index),
"shortname": get_text(line, shortname_index),
"group": get_text(line, group_index),
"namespace": get_text(line, namespace_index),
"kind": get_text(line, kind_index)
})
print(resources)
And the output is(formatted):
[
{
'name': 'bindings',
'shortname': 'no-value',
'group': 'no-value',
'namespace': 'true',
'kind': 'Binding'
},
{
'name': 'pods',
'shortname': 'po',
'group': 'no-value',
'namespace': 'true',
'kind': 'Pod'
},
{
'name': 'deployments',
'shortname': 'deploy',
'group': 'apps',
'namespace': 'true',
'kind': 'Deployment'
}
]

AWS policy statement returning no conditions when explicit conditions are set

I created a policy out of a policy document json and I'm trying to get the condition_entries from each statement. In the following example I only have one statement and one condition, but for some reasons I'm getting an empty list returned. What am I doing wrong?
from policyuniverse.policy import Policy
def test_conditions_entries(self):
policy_document = {
'Version': '2012-10-17',
'Statement': [{
'Effect': 'Allow',
'Action': 'iam:DeleteUser',
'Resource': '*',
'Condition': {'StringLike': {'iam:ResourceTag/status': 'terminated'}}
}]
}
p = Policy(policy_document)
for statement in p.statements:
print(statement.statement)
print(statement.condition_entries)
{'Effect': 'Allow', 'Action': 'iam:DeleteUser', 'Resource': '*', 'Condition': {'StringLike': {'iam:ResourceTag/status': 'terminated'}}}
[]
It looks like iam:ResourceTag/status is not working.
The following does not work:
{"StringLike": {"iam:ResourceTag/status": "terminated"}
The following does work.
Condition = {
'StringLike': {
'AWS:SourceOwner': '012345678910'
}
}
hope this help you some extend.

Set customer ID for Google Adwords API

I try to use the Google Adwords API, with the official library here : https://github.com/googleads/googleads-python-lib
I use an Manager Account on Google Adwords and want to work with my client's accounts.
I can get all the the Adwords account ID (like 123-456-7891) but I don't know how to pass the account ID to my Google Adwords functions as a parameter.
Here's my main function :
def main(argv):
adwords_client = adwords.AdWordsClient.LoadFromStorage(path="googleads.yaml")
add_campaign(adwords_client)
I see any Account ID parameter in the official samples, as :
import datetime
import uuid
from googleads import adwords
def add_campaign(client):
# Initialize appropriate services.
campaign_service = client.GetService('CampaignService', version='v201809')
budget_service = client.GetService('BudgetService', version='v201809')
# Create a budget, which can be shared by multiple campaigns.
budget = {
'name': 'Interplanetary budget #%s' % uuid.uuid4(),
'amount': {
'microAmount': '50000000'
},
'deliveryMethod': 'STANDARD'
}
budget_operations = [{
'operator': 'ADD',
'operand': budget
}]
# Add the budget.
budget_id = budget_service.mutate(budget_operations)['value'][0][
'budgetId']
# Construct operations and add campaigns.
operations = [{
'operator': 'ADD',
'operand': {
'name': 'Interplanetary Cruise #%s' % uuid.uuid4(),
# Recommendation: Set the campaign to PAUSED when creating it to
# stop the ads from immediately serving. Set to ENABLED once you've
# added targeting and the ads are ready to serve.
'status': 'PAUSED',
'advertisingChannelType': 'SEARCH',
'biddingStrategyConfiguration': {
'biddingStrategyType': 'MANUAL_CPC',
},
'endDate': (datetime.datetime.now() +
datetime.timedelta(365)).strftime('%Y%m%d'),
# Note that only the budgetId is required
'budget': {
'budgetId': budget_id
},
'networkSetting': {
'targetGoogleSearch': 'true',
'targetSearchNetwork': 'true',
'targetContentNetwork': 'false',
'targetPartnerSearchNetwork': 'false'
},
# Optional fields
'startDate': (datetime.datetime.now() +
datetime.timedelta(1)).strftime('%Y%m%d'),
'frequencyCap': {
'impressions': '5',
'timeUnit': 'DAY',
'level': 'ADGROUP'
},
'settings': [
{
'xsi_type': 'GeoTargetTypeSetting',
'positiveGeoTargetType': 'DONT_CARE',
'negativeGeoTargetType': 'DONT_CARE'
}
]
}
}, {
'operator': 'ADD',
'operand': {
'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(),
'status': 'PAUSED',
'biddingStrategyConfiguration': {
'biddingStrategyType': 'MANUAL_CPC'
},
'endDate': (datetime.datetime.now() +
datetime.timedelta(365)).strftime('%Y%m%d'),
# Note that only the budgetId is required
'budget': {
'budgetId': budget_id
},
'advertisingChannelType': 'DISPLAY'
}
}]
campaigns = campaign_service.mutate(operations)
How can I tell Adwords API in which account I want to add this campaign ?
Thanks for your help !
OK my bad, I missed a documentation method (http://googleads.github.io/googleads-python-lib/googleads.adwords.AdWordsClient-class.html#SetClientCustomerId).
# ID of your customer here
CUSTOMER_SERVICE_ID = '4852XXXXX'
# Load customer account access
client = adwords.AdWordsClient.LoadFromStorage(path="googleads.yaml")
client.SetClientCustomerId(CUSTOMER_SERVICE_ID)
And the customer ID is now associate with the AdwordsClient variable as "client" set as parameters for other functions.

Adding a New Language Locale to Django

I'm trying to add site translations for a few African languages that Django 1.6.8 does not support. I don't need the admin to to work in those languages, but I do need to support them.
My site already has working translations in 25 languages from languages officially supported by Django and they are divided by subdomain, so de.mysite.com is German. I'm using subdomain middleware to set the locale based on the subdomain, like so:
class SubDomainLanguage(object):
def process_request(self, request):
prefix = None
try:
prefix = request.META['HTTP_HOST'].split('.')[0]
if prefix == 'no':
prefix = 'nb'
request.session['django_language'] = prefix
except KeyError:
pass
if not prefix:
request.session['django_language'] = 'en'
Various web searches have led me to a point where it feels like I'm close to adding support for these languages, but visiting yo.mysite.com gives me the English version of the site, so something's missing (de.mysite.com is in German, as intended).
Yoruba translations exist in locale/yo/LC_MESSAGES/django.mo and django.po, and python manage.py compilemessages worked fine.
Here are the related lines from my settings.py file:
from django.conf import global_settings
from django.utils.translation import gettext_noop
MIDDLEWARE_CLASSES = (
...
'subdomainmiddleware.SubDomainLanguage',
'django.middleware.locale.LocaleMiddleware',
...
)
global_settings.LANGUAGES += ('ak', gettext_noop('Akan'))
global_settings.LANGUAGES += ('ig', gettext_noop('Igbo'))
global_settings.LANGUAGES += ('rw', gettext_noop('Rwanda'))
global_settings.LANGUAGES += ('sn', gettext_noop('Shona'))
global_settings.LANGUAGES += ('yo', gettext_noop('Yoruba'))
global_settings.LANGUAGES += ('zu', gettext_noop('Zulu'))
EXTRA_LANG_INFO = {
'ak': {
'bidi': False,
'code': 'ak',
'name': 'Akan',
'name_local': u'Akan'
},
'ig': {
'bidi': False,
'code': 'ig',
'name': 'Igbo',
'name_local': u'Asụsụ Igbo'
},
'rw': {
'bidi': False,
'code': 'rw',
'name': 'Rwanda',
'name_local': u'Kinyarwanda'
},
'sn': {
'bidi': False,
'code': 'sn',
'name': 'Shona',
'name_local': u'chiShona'
},
'yo': {
'bidi': False,
'code': 'yo',
'name': 'Yoruba',
'name_local': u'èdè Yorùbá'
},
'zu': {
'bidi': False,
'code': 'zu',
'name': 'Zulu',
'name_local': u'isiZulu'
},
}
import django.conf.locale
LANG_INFO = dict(django.conf.locale.LANG_INFO.items() + EXTRA_LANG_INFO.items())
django.conf.locale.LANG_INFO = LANG_INFO
What could be missing? Or is there maybe something in the wrong order?

Categories