Code Bug Fix: Could not build url for endpoint ‘topic’ with values [‘type’]. Did you mean ‘topic_func’ instead?

Original Source Link

I am trying to create dynamic urls in jinja and I need to pass the selected value from the html page to the flask to create the new web page.

I have topics in a dropdown menu and when I click the link, the information needs to be passed to the flask that which link was selected and what will be displayed on that page but an error occurred saying could not build endpoint for url. Any help will be highly appreciated. Thanks in advance!!

The dashboard.py file is here:

@app.route('/')
def home():
     #topic is a list of topics for the dropdown menu
     return render_template("home.html",topic=topics)
@app.route('/topic', methods=['GET', 'POST'])
def topic_func():
    result = request.args.get('type')
    print(result) #should print what was the topic that was clicked in the dropdown menu 
    return render_template(index.html, value=result)

This is home.html and also I am unable to get the value of type. It is printing {{each}} when it should print the value of the topic selected. How can I solve this?:

<div class="dropdown-content">

{% for each in topics %}

      <a href="{{url_for('topic', type='{{each}}')}}">{{each}}</a>

{% endfor %}

</div>

You should rather structure your code like this:

<div class="dropdown-content">

    {% for each in topics %}

          <a href="{{url_for('topic_func', type='')}}{{each}}">{{each}}</a>

    {% endfor %}

</div>

Remarks two things:

  1. In url_for I replaced the route topic with the the function topic_func. This is because url_for looks for a function. So you have to pass it the name of a function.

  2. I moved the value to send {{each}}, after the two braces of url_for. The reason is that by leaving them inside the quotes, the function url_for does not understand it as a jinja variable but it considers that it is the exact value that you want to send. So you’re going to have, on the python side:

Python:

@app.route('/topic', methods=['GET', 'POST']) 
def topic_func():
    result = request.args.get('type')
    print(result)  # {{each}}

Tagged : / / /

Code Bug Fix: how to clone row and create new radio button name (keep every radio button group name unique)

Original Source Link

how to clone new row (the sub element radio button name )

html jinja2 (use for loop from json file item that use python process make)
like

                {% for i in data %}
                    <tr class="tr_clone">
                        <td id="td_id_{{ loop.index }}" scope="row" class="member_data_title td_id">
                            <span class="td_id_span">{{loop.index}}</span>
                        </td>
                        <td id="td_logic_{{ loop.index }}" scope="row" class="member_data_title td_logic">
                            <label for="login_and">AND</label>
                            <input type="radio" id="login_and_{{ loop.index }}" name="logic_{{ loop.index }}" {{'value=1 checked="checked" ' if i['Logic'] == 'AND' else 'value="0"'}}>
                            <label for="logic_not">NOT</label>
                            <input type="radio" id="login_not_{{ loop.index }}" name="logic_{{ loop.index }}" {{'value=1 checked="checked" ' if i['Logic'] == 'NOT' else 'value="0"'}}>
                        </td>
                        <td id="td_StudyDescription_{{ loop.index }}" scope="row" class="member_data_title td_StudyDescription">
                            <input type="text" id="StudyDescription_{{ loop.index }}" name="StudyDescription_{{ loop.index }}" value="{{i["StudyDescription"]}}">
                        </td>
                        <td id="td_SeriesDescription_{{ loop.index }}" scope="row" class="member_data_title td_SeriesDescription">
                            <input type="text" id="SeriesDescription_{{ loop.index }}" name="SeriesDescription_{{ loop.index }}" value="{{i["SeriesDescription"]}}">
                        </td>
                        <td id="td_ImageComments_{{ loop.index }}" scope="row" class="member_data_title td_ImageComments">
                            <input type="text" id="ImageComments_{{ loop.index }}" name="ImageComments_{{ loop.index }}" value="{{i["ImageComments"]}}">
                        </td>

                        <td id="td_btnRuleDelete_{{ loop.index }}" scope="row" class="member_data_title td_btnRuleDelete">
                            <input type="button" id="btnRuleDelete_{{ loop.index }}" name="btnRuleDelete_{{ loop.index }}" value="Delete" class="td_btnRuleDelete_btn">
                        </td>
                    </tr>
                {% endfor %}

script part

 <script>
      $(document).ready(function () {
          $('#btnAddRow').click(function(){
            var $lastRow = $("tr:last"); //grab row before the last row
            var $newRow = $lastRow.clone(); //clone it
            $newRow.find(":text").val(""); //clear out textbox values
            $newRow.find(".td_id_span").text(""); //clear out textbox values
            $newRow.find(".td_btnRuleDelete_btn").remove()
            $newRow.find("radio").attr("name","new")
            $lastRow.after($newRow); //add in the new row at the end
          })

          $('.td_btnRuleDelete_btn').click(function(){
               $(this).closest('tr').remove();
          })
      })
    </script>

hope want add rule new row (raido button part) like

   <tr>
    <td id="td_logic_4" scope="row" class="member_data_title td_logic">
        <label for="login_and">AND</label>
        <input type="radio" id="login_and_4" name="login_and_4" value="" checked>
        <label for="logic_not">NOT</label>
        <input type="radio" id="login_not_4" name="login_not_4" value="">
    </td>
   </tr>

before i click Add Rule
enter image description here
after i click Add Rule
enter image description here

my record id 3 radio button miss name ,then radio check turn to empty

Tagged : / / / /

Server Bug Fix: When using an Ansible playbook, how do you store and use a password containing quotes or other metacharacters without them being interpereted?

Original Source Link

My company uses Ansible (which I am a novice at) and we have a playbook and a related role for joining new Linux machines to AD. Our admin accounts have their passwords rolled three times a day, and we can’t set them ourselves. The Ansible playbook works so long as there is not a ' (single quote) in the password. There may be other characters that cause it to break, but I know that ' does it for sure.

Here are the relevant bits of the scripts:

cat setup-ad.yml

---
- hosts: "{{ hosts }}"

  vars_prompt:
  - name: "username"
    prompt: "Enter admin account"
    private: no

  - name: "password"
    prompt: "Enter Password"
    unsafe: yes
    private: yes

  vars:
    domain: "{{ 'mycompany.com' }}"
    passwd: "{{ password | regex_escape() }}"

  roles:
  - join-ad

grep -B2 -A3 'passwd' ./roles/join-ad/tasks/main.yml

  - name: join to active directory
    command: net ads join MYCOMPANY.COM -U {{ username }}@MYCOMPANY.COM%'{{ passwd }}' createcomputer=Restricted/Servers/Unix --request-timeout=120 --no-dns-updates
    no_log: false
    when: ansible_distribution_major_version >= 6

  - name: join to active directory
    command: net ads join MYCOMPANY.COM -U {{ username }}@MYCOMPANY.COM%'{{ passwd }}' createcomputer=Restricted/Servers/Unix --request-timeout=120
    no_log: false
    when: ansible_distribution_major_version <= 5

The error we get is:

TASK [join-ad : join to active directory] ************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ValueError: No closing quotation
fatal: [newserver.mycompany.com]: FAILED! => {"changed": false, "module_stderr": "Shared connection to newserver.mycompany.com closed.rn", "module_stdout": "Traceback (most recent call last):rn  File "/root/.ansible/tmp/ansible-tmp-1590785720.2-224244797633747/AnsiballZ_command.py", line 102, in <module>rn    _ansiballz_main()rn  File "/root/.ansible/tmp/ansible-tmp-1590785720.2-224244797633747/AnsiballZ_command.py", line 94, in _ansiballz_mainrn    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)rn  File "/root/.ansible/tmp/ansible-tmp-1590785720.2-224244797633747/AnsiballZ_command.py", line 40, in invoke_modulern    runpy.run_module(mod_name='ansible.modules.commands.command', init_globals=None, run_name='__main__', alter_sys=True)rn  File "/usr/lib64/python2.7/runpy.py", line 176, in run_modulern    fname, loader, pkg_name)rn  File "/usr/lib64/python2.7/runpy.py", line 82, in _run_module_codern    mod_name, mod_fname, mod_loader, pkg_name)rn  File "/usr/lib64/python2.7/runpy.py", line 72, in _run_codern    exec code in run_globalsrn  File "/tmp/ansible_command_payload_4D4oFT/ansible_command_payload.zip/ansible/modules/commands/command.py", line 344, in <module>rn  File "/tmp/ansible_command_payload_4D4oFT/ansible_command_payload.zip/ansible/modules/commands/command.py", line 263, in mainrn  File "/usr/lib64/python2.7/shlex.py", line 279, in splitrn    return list(lex)rn  File "/usr/lib64/python2.7/shlex.py", line 269, in nextrn    token = self.get_token()rn  File "/usr/lib64/python2.7/shlex.py", line 96, in get_tokenrn    raw = self.read_token()rn  File "/usr/lib64/python2.7/shlex.py", line 172, in read_tokenrn    raise ValueError, "No closing quotation"rnValueError: No closing quotationrn", "msg": "MODULE FAILUREnSee stdout/stderr for the exact error", "rc": 1}

PLAY RECAP *******************************************************************************************************
newserver.mycompany.com : ok=9    changed=0    unreachable=0    failed=1    skipped=2    rescued=0    ignored=0

Okay, so the issue is that at some point the ' is being interpreted as the beginning of a quoted series of characters, rather than as simply part of the password. My problem is I don’t know how to get Ansible? Python? YAML? Jinja? to treat the string of characters the user inputs as nothing more than a string of characters. Is “string literal” the correct term here?

If I ssh to the target server and run the net ads join command manually, and let it prompt for my password, it will work even with a ' in it, so at the very least I know it’s not the Samba command that’s the issue.

The things I’ve tried (which haven’t helped) are:

  • Add ‘hard quotes’ around {{ passwd }}
  • Add unsafe: yes to the password definition
  • Add passwd: "{{ password | regex_escape() }}" to escape metacharacters
  • Lots of internet searching on Stack and Google

Any and all help would be appreciated.

This might be what you’re looking for

- command: "net ads join MYCOMPANY.COM
            -U {{ username }}@MYCOMPANY.COM%{{ passwd|quote }}
            createcomputer=Restricted/Servers/Unix --request-timeout=120"

See YAML gotcha and String filters.

Tagged : / / / /

Code Bug Fix: Using ansible, uri module, registered json results, loop over only singular/unique values in returned json data

Original Source Link

I’m probably overthinking this or missing something extremely obvious…and I apologize in advance for my long ass problem description. 🙂

My situation is I’m using the ansible uri module to query the netbox api for site info. I’m then using that output looped within a jinja2 template to match devices to their respective sites to build a configuration. The problem is some sites have multiple devices and my question is, in jinja2 is there a way to say only match once or match on unique items in the loop?

Example:

- name:                1.0 Get Netbox devices marked as status 'staged'
  uri:
    url:               "{{ netbox }}/api/dcim/devices/?limit=0&status=staged"
    method:            GET
    return_content:    yes
  register:            get_devices

- name:                2.0 Get site info per device
  uri:
    url:               "{{ netbox }}/api/dcim/sites/?id={{ item.site.id }}"
    method:            GET
    return_content:    yes
  register:            get_all_sites
  loop:                "{{ get_devices.json.results }}"

- name:                "Build configurations loop"
  include_tasks:       configuration.yml
  loop:                "{{ get_devices.json.results }}"
  loop_control:
    loop_var:        device_item

So all is good up to this point. Now upon calling the jinja2 template configuration.j2 here is where my issue starts. The template looks as follows:

{% for device_all_sites in get_all_sites.results %}
{% for device_site in device_all_sites.json.results %}
{% if device_site.id == device_item.site.id %}
snmp-server location {{ device_site.physical_address }}
{% endif %}
{% endfor %}
{% endfor %}

The problem is if a site has multiple devices associated with it, I end up with multiple iterations of device_site.id matches because the site ends up in the json output multiple times from playbook step 2 above. Two devices in the same site end up registering twice in the output.

Is there a way to say, only match one id per loop? Or provide uniqueness to the results registered in get_all_sites?

Appreciate any comments or solutions in advance!

Thanks!

Tagged : / /

Code Bug Fix: jinja2.exceptions.UndefinedError – Trying to reach a specific value

Original Source Link

I’m trying to parse a JSON object which is –

{
  "ticket": {
    "ticket_id": "HGAS52GH98JK",
    "ticket_status": 1,
    "ticket_date": "Wed, 13 May 2020 20:40 PM",
    "ticket_replied": false,
    "ticket_reply_message": "None",
    "ticket_issued_by": "65313696-d0a0-4019-8f89-e5e8ab01d6b7",
    "ticket_issued_to": "1e76b45c-67cd-4100-ae43-d8adf85d4362"
  },
  "messages": [
    {
      "msg_ticket_id": "HGAS52GH98JK",
      "msg_id": "2d4c0968-337b-4401-ad09-80e8890a5dce",
      "msg_sender": "65313696-d0a0-4019-8f89-e5e8ab01d6b7",
      "msg_date": "Wed, 13 May 2020 20:48 PM",
      "msg": "test_msg1"
    },
    {
      "msg_ticket_id": "HGAS52GH98JK",
      "msg_id": "2d4c0968-337b-4401-ad09-80e88f0a7dce",
      "msg_sender": "65313696-d0a0-4019-8f89-e5e8ab01d6b7",
      "msg_date": "Wed, 13 May 2020 20:59 PM",
      "msg": "test_msg3"
    },
    {
      "msg_ticket_id": "HGAS52GH98JK",
      "msg_id": "2d4c0968-337b-4401-ad05-80e8890a5dce",
      "msg_sender": "65313696-d0a0-4019-8f89-e5e8ab01d6b7",
      "msg_date": "Wed, 13 May 2020 20:49 PM",
      "msg": "test_msg2"
    }
  ]
}

Firstly I need to get into ‘messages’ and then get id and other values of each of message. To do so I use –

{% if ticket_data["messages"] %}
    {% for msg in ticket_data["messages"] %}
        {{ ticket_data['messages'][msg]['msg_id'] }}
    {% endfor %}
{% endif %}

But I do get an error which is jinja2.exceptions.UndefinedError: list object has no element {'msg_ticket_id': 'HGAS52GH98JK', 'msg_id': '2d4c0968-337b-4401-ad09-80e8890a5dce', 'msg_sender': '65313696-d0a0-4019-8f89-e5e8ab01d6b7', 'msg_date': 'Wed, 13 May 2020 20:48 PM', 'msg': 'test_msg1'}

What I’m doing wrong? what’s the proper way to get a value from it?
I tried using {{ ticket_data['messages'][msg]['msg_id'] }} In the for loop, then I do get an ID from the message but 3 times because there are 3 messages defined in the JSON.

I was able to fix it with:

{% if ticket_data["messages"] %}
    {% for msg in ticket_data["messages"] %}
        {{ msg['msg'] }}
    {% endfor %}
{% endif %}

Tagged : / /

Code Bug Fix: Jinja2 parsing a JSON object, can’t get a values from it

Original Source Link

I’m trying to parse a string. I have two variants:

  1. Not loaded with json.loads()
  2. loaded

They look like:

1.

{"ticket_info": {"ticket_id": "HGAS52GH98JK", "ticket_status": 1, "ticket_date": "Wed, 13 May 2020 20:40 PM", "ticket_replied": false, "ticket_reply_message": null, "ticket_issued_by": "65313696-d0a0-4019-8f89-e5e8ab01d6b7", "ticket_issued_to": "1e76b45c-67cd-4100-ae43-d8adf85d4362"}, "messages": [{"msg_ticket_id": "HGAS52GH98JK", "msg_id": "2d4c0968-337b-4401-ad09-80e8890a5dce", "msg_sender": "65313696-d0a0-4019-8f89-e5e8ab01d6b7", "msg_date": "Wed, 13 May 2020 20:48 PM", "msg": "test_msg1"}, {"msg_ticket_id": "HGAS52GH98JK", "msg_id": "2d4c0968-337b-4401-ad09-80e88f0a7dce", "msg_sender": "65313696-d0a0-4019-8f89-e5e8ab01d6b7", "msg_date": "Wed, 13 May 2020 20:59 PM", "msg": "test_msg3"}, {"msg_ticket_id": "HGAS52GH98JK", "msg_id": "2d4c0968-337b-4401-ad05-80e8890a5dce", "msg_sender": "65313696-d0a0-4019-8f89-e5e8ab01d6b7", "msg_date": "Wed, 13 May 2020 20:49 PM", "msg": "test_msg2"}]}

  1. {'ticket_info': {'ticket_id': 'HGAS52GH98JK', 'ticket_status': 1, 'ticket_date': 'Wed, 13 May 2020 20:40 PM', 'ticket_replied': False, 'ticket_reply_message': 'None', 'ticket_issued_by': '65313696-d0a0-4019-8f89-e5e8ab01d6b7', 'ticket_issued_to': '1e76b45c-67cd-4100-ae43-d8adf85d4362'}, 'messages': [{'msg_ticket_id': 'HGAS52GH98JK', 'msg_id': '2d4c0968-337b-4401-ad09-80e8890a5dce', 'msg_sender': '65313696-d0a0-4019-8f89-e5e8ab01d6b7', 'msg_date': 'Wed, 13 May 2020 20:48 PM', 'msg': 'test_msg1'}, {'msg_ticket_id': 'HGAS52GH98JK', 'msg_id': '2d4c0968-337b-4401-ad09-80e88f0a7dce', 'msg_sender': '65313696-d0a0-4019-8f89-e5e8ab01d6b7', 'msg_date': 'Wed, 13 May 2020 20:59 PM', 'msg': 'test_msg3'}, {'msg_ticket_id': 'HGAS52GH98JK', 'msg_id': '2d4c0968-337b-4401-ad05-80e8890a5dce', 'msg_sender': '65313696-d0a0-4019-8f89-e5e8ab01d6b7', 'msg_date': 'Wed, 13 May 2020 20:49 PM', 'msg': 'test_msg2'}]}

My Python code:

if ticket:
    "~ Engine for JSON data processing ~"

    _ticket_data_ = _tickets_.get_ticket(ticket.ticket_id)
    ticket_data = json.loads(str(_ticket_data_.replace('null', '"None"')))


    return render_template('index.html',
                           title='Main profile',
                           template='dashboard-template',
                           current_user=current_user,
                           ticket_data=ticket_data,
                           body="You are now logged in!")

When I pass the loaded one I can get these results:

The Json I passed in HTML is:

{'ticket_info': {'ticket_id': 'HGAS52GH98JK', 'ticket_status': 1, 'ticket_date': 'Wed, 13 May 2020 20:40 PM', 'ticket_replied': False, 'ticket_reply_message': 'None', 'ticket_issued_by': '65313696-d0a0-4019-8f89-e5e8ab01d6b7', 'ticket_issued_to': '1e76b45c-67cd-4100-ae43-d8adf85d4362'}, 'messages': [{'msg_ticket_id': 'HGAS52GH98JK', 'msg_id': '2d4c0968-337b-4401-ad09-80e8890a5dce', 'msg_sender': '65313696-d0a0-4019-8f89-e5e8ab01d6b7', 'msg_date': 'Wed, 13 May 2020 20:48 PM', 'msg': 'test_msg1'}, {'msg_ticket_id': 'HGAS52GH98JK', 'msg_id': '2d4c0968-337b-4401-ad09-80e88f0a7dce', 'msg_sender': '65313696-d0a0-4019-8f89-e5e8ab01d6b7', 'msg_date': 'Wed, 13 May 2020 20:59 PM', 'msg': 'test_msg3'}, {'msg_ticket_id': 'HGAS52GH98JK', 'msg_id': '2d4c0968-337b-4401-ad05-80e8890a5dce', 'msg_sender': '65313696-d0a0-4019-8f89-e5e8ab01d6b7', 'msg_date': 'Wed, 13 May 2020 20:49 PM', 'msg': 'test_msg2'}]}

I parse it with:

{% if ticket_data %} 
    {% for ticket in ticket_data["ticket_info"] %}
      <h3>variables... {{ ticket }}</h3>
      {% if ticket["ticket_issued_to"] == current_user.public_id %}
    <!-- I cannot reach this or any other variable with ticket[ANYVAR]... -->
      {% endif %}
    {% endfor %}
{% endif %}

Results:

variables... ticket_id
variables... ticket_status
variables... ticket_date
variables... ticket_replied
variables... ticket_reply_message
variables... ticket_issued_by
variables... ticket_issued_to

But when I try to reach a value inside a for loop with:

<h2> Receiver - {{ticket["ticket_issued_to"]}}</h2>

I just get the value as blank.

You are actually trying to get value from the wrong place of Dict.

Let’s walk through the dictionary and see where actually the code is looking.

This is your ticket data:

{
  "ticket_info": {
    "ticket_id": "HGAS52GH98JK",
    "ticket_status": 1,
    "ticket_date": "Wed, 13 May 2020 20:40 PM",
    "ticket_replied": false,
    "ticket_reply_message": null,
    "ticket_issued_by": "65313696-d0a0-4019-8f89-e5e8ab01d6b7",
    "ticket_issued_to": "1e76b45c-67cd-4100-ae43-d8adf85d4362"
  },
  "messages": [
    {
      "msg_ticket_id": "HGAS52GH98JK",
      "msg_id": "2d4c0968-337b-4401-ad09-80e8890a5dce",
      "msg_sender": "65313696-d0a0-4019-8f89-e5e8ab01d6b7",
      "msg_date": "Wed, 13 May 2020 20:48 PM",
      "msg": "test_msg1"
    },
    {
      "msg_ticket_id": "HGAS52GH98JK",
      "msg_id": "2d4c0968-337b-4401-ad09-80e88f0a7dce",
      "msg_sender": "65313696-d0a0-4019-8f89-e5e8ab01d6b7",
      "msg_date": "Wed, 13 May 2020 20:59 PM",
      "msg": "test_msg3"
    },
    {
      "msg_ticket_id": "HGAS52GH98JK",
      "msg_id": "2d4c0968-337b-4401-ad05-80e8890a5dce",
      "msg_sender": "65313696-d0a0-4019-8f89-e5e8ab01d6b7",
      "msg_date": "Wed, 13 May 2020 20:49 PM",
      "msg": "test_msg2"
    }
  ]
}

This is your ticket_data[“ticket_info”]:

{
  "ticket_id": "HGAS52GH98JK",
  "ticket_status": 1,
  "ticket_date": "Wed, 13 May 2020 20:40 PM",
  "ticket_replied": false,
  "ticket_reply_message": null,
  "ticket_issued_by": "65313696-d0a0-4019-8f89-e5e8ab01d6b7",
  "ticket_issued_to": "1e76b45c-67cd-4100-ae43-d8adf85d4362"
}

when you run below loop:

{% for ticket in ticket_data["ticket_info"] %}

It actually goes through the list of keys of ticket_info dict and that’s why while printing the ticket variable in the loop you are actually getting the list of keys in the output so if you want to get the value you should try this:

{% if ticket_data %} 
    {% for ticket in ticket_data["ticket_info"] %}
      <h3>variable key... {{ ticket }}</h3>
      <h3>variable value... {{ ticket_data["ticket_info"][ticket] }}</h3>
    {% endfor %}
{% endif %}

You will get both the key and value using the above code. You can modify your “if” statement accordingly.

Hope this helps!!

Tagged : / /

Server Bug Fix: ansible/jinja2 reject all items from list of dicts with specific attribute

Original Source Link

I have a list of dicts like this:

list_of_dicts:
  - name: Item1
  - name: Item2
    type: special
  - name: Item3
  - name: Item4
    type: small

As you can see, not all items have a type attribute. If no type attribute is set, that means the item is of the default type.

I would like to select all items which are NOT of type special.

I’ve tried this: list_of_dicts | rejectattr('type', 'equalto', 'special')

Unfortunately, this fails with a AnsibleUndefinedVariable: 'dict object' has no attribute 'type' error because some of the items do not have a type.

What is a good way to solve this?

Tagged : /