Sylius : An exception has been thrown during the rendering of a template ("") in #SyliusShop\Product\Show\_inventory.html.twig at line 4 - sylius

i have this exception :
An exception has been thrown during the rendering of a template ("") in #SyliusShop\Product\Show_inventory.html.twig at line 4.
500 Internal Server Error - Twig_Error_Runtime
1 linked Exception: NotFoundHttpException ยป
and this is the file that throws the exception :
ShopBundle/Resources/views/Product/Show/_inventory.html.twig:
{% if product.simple and not sylius_inventory_is_available(product.firstVariant) %}
{% include '#SyliusShop/Product/Show/_outOfStock.html.twig' %}
{% else %}
{% render(url('sylius_shop_cart_item_add', {'template': '#SyliusShop/Product/Show/_addToCart.html.twig', 'productId': product.id})) %}
{% endif %}
ShopBundle/Resources/config/routing/cart.yml:
sylius_shop_cart_item_add:
path: /add
methods: [GET, POST]
defaults:
_controller: sylius.controller.cart_item:addAction
_sylius:
factory:
method: createForProduct
arguments: [expr:service('sylius.repository.product').find($productId)]
form:
type: sylius_cart_item
options:
product: expr:service('sylius.repository.product').find($productId)
template: $template
redirect:
route: sylius_shop_cart_summary
parameters: {}
flash: sylius.cart.item_add_completed
i make sure that the product id is not null , what can be the problem ?

Related

Gramex - DBAuth Login only when user is active

I am trying to implement a way by which I can check the value of an is_active column from user database before letting the user log in. So along with the password check, I also want to check if is_active column is True, only then the user must be able to login, otherwise I want restrict login and show an error that "The user is inactive"(even if the password is correct).
I went through the Gramex documentation but could not find a way to configure this requirement.
Is there any way to implement this in DBAuth?
If you want to validate if the is_active column in the database is true, and to prevent login before the fact, use prepare:. For example:
url:
login:
pattern: /login/
handler: DBAuth
kwargs:
prepare: mymodule.check_active(args)
...
... where mymodule.py has:
def check_active(args)
if handler.request.method == 'POST':
is_active = gramex.data.filter(
url, table='user', args={'user': args['user'], 'is_active': [True]})
if not is_active:
raise HTTPError(403, 'Cannot log in as inactive user')
More flexible solution. Create a subclass of DBAuth called ValidatedDBAuth:
import gramex.data
from tornado.gen import coroutine
from gramexenterprise.handlers import DBAuth
from gramex.config import variables
class ValidatedDBAuth(DBAuth):
#coroutine
def post(handler):
user = handler.get_argument('user')
is_active = gramex.data.filter(
variables['CONNECTION_STRING'],
table='user',
args={'user': [user]}
)['is_active'].iloc[0]
if is_active:
yield super().post()
else:
handler.redirect('/login/?msg=inactive')
Now use this instead of your DBAuth. For example:
url:
login:
pattern: /login/
handler: mymodule.ValidatedDBAuth
kwargs:
... # Same as for DBAuth
You can copy the default auth.template.html locally as custom-login.html.
Then you can check if the user is already logged in (i.e. is_active) by checking handler.current_user. For example:
{% set is_active = handler.current_user %}
{% if not is_active %}
<p>The user is inactive. You can't log in.</p>
{% else %}
... continue with default form
{% end %}
In your gramex.yaml, you could add template: $YAMLPATH/custom-login.html like this:
login:
pattern: /login/
handler: DBAuth
kwargs:
url: $YAMLPATH/auth.xlsx
user:
column: user
password:
column: password
template: $YAMLPATH/custom-login.html
NOTE: By only allowing logged-in users to log in, no user will be able to log in for the first time. So you'll need some mechanism to figure out how to let users log in for the first time.

Retry Ansible URI PUT API Call with a POST API Call

Hello I am trying to run a PUT API call via Ansible URI module for a particular API Endpoint in my application, using a dictionary that contains the json files and that is defined as:
example: { 'example1' : 'v1', 'example2': 'v2''}
- name: Update existing
block:
- name: update existing
uri:
url: "{{url}}/api/{{item.key}}/"
method: PUT
body: "{{ lookup('file', 'example/{{item.key}}/{{item.value}}.json') }}"
status_code: 200
body_format: json
headers:
Content-Type: "application/json"
Authorization: "Token {{ token.json.token }}"
with_dict: "{{ example }}"
register: result
For the PUT api call, this api endpoint will fail is the {{item.key}} does not exist, e.g. if
"{{url}}/api/{{item.key}}/" endpoint does not exist, hence it will give a 4xx error.
Given the task fails and I get a 4xx error when the api endpoint for the item does not exist, I want to run a POST command for that same json file.
How can I do this in ansible, to retry a task that failed but only specifically for that {{item.key}} and {{item.value}} in dictionary?
or
Is there a better way to do this to retry a failed PUT with a POST command
I want to use the ansible URI module
Thanks!
You can ignore the error case and then loop through result.results with filtering to keep only errors. You can have access to the original item with item.item:
- name: update existing with PUT
uri:
url: "{{url}}/api/{{item.key}}/"
method: PUT
body: "{{ lookup('file', 'example/{{item.key}}/{{item.value}}.json') }}"
status_code:
- 200
- 404 # supposing it's the "normal" error case
body_format: json
headers:
Content-Type: "application/json"
Authorization: "Token {{ token.json.token }}"
loop: "{{ example | items2dict }}"
register: result
- name: update existing with POST
uri:
url: "{{url}}/api/{{item.item.key}}/"
method: POSTT
body: "{{ lookup('file', 'example/{{item.item.key}}/{{item.item.value}}.json') }}"
status_code: 200
body_format: json
headers:
Content-Type: "application/json"
Authorization: "Token {{ token.json.token }}"
loop: "{{ result.results | rejectattr('status', '200') }}" # filter out 200 status from previous task

gcloud deployment-manager undefined properties: UndefinedError: 'properties' is undefined

There is sample code here that uses the following code snippet to handle undefined properties.
{% if properties["cidr"] is defined %}
{% set cidr = properties["cidr"] %}
{% else %}
{% set cidr = "10.10.0.0/16" %}
{% endif %}
github deployment-manager example
However, when I attempt to use similar code:
{% if properties['prod'] is defined %}
{% set machine_type = 'n1-highmem-8' %}
{% set num_nodes = 3 %}
{% else %}
{% set machine_type = 'g1-small' %}
{% set num_nodes = 1 %}
{% endif %}
and deploy as follows:
gcloud deployment-manager deployments create xxx --template kubernetes.jinja --automatic-rollback-on-error --preview
I get the following error:
- code: MANIFEST_EXPANSION_USER_ERROR location: /deployments/xxx/manifests/manifest-1597981115450 message: |-
Manifest expansion encountered the following errors: Exception in kubernetes.jinja
Traceback (most recent call last):
return template.render(resource)
return self.environment.handle_exception(exc_info, True)
reraise(exc_type, exc_value, tb)
File "<template>", line 19, in top-level template code
return obj[argument]
UndefinedError: 'properties' is undefined
Resource: kubernetes.jinja Resource: config
When I deploy with properties it works.
gcloud deployment-manager deployments create xxx --template kubernetes.jinja --automatic-rollback-on-error --preview --properties prod:false
How can I setup a jinja script to have default values and/or detect missing properties without throwing an exception?
UPDATE:
Adding ANY property, even a different one seems to be enough to have the script execute. It appears the properties attribute is COMPLETELY missing by default!
gcloud deployment-manager deployments create xxx --template kubernetes.jinja --automatic-rollback-on-error --preview --properties adsfsdfsdf:Asdfasdfasdf
You need to define properties either in the config that uses the template or when deploying from the command line.
See: https://cloud.google.com/deployment-manager/docs/configuration/templates/define-template-properties
E.g.
gcloud deployment-manager deployments create xxx \
--template=kubernetes.jinja \
--properties=prod:...

python 3 flask how to debug 400 Bad Request: The browser (or proxy) sent a request that this server could not understand

New to Python 3.7 RESTFUl API. In the following POST endpoint, I keep getting the following error message in the POST endpoint, but the GET endpoint works fine.
Exception in _query: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
Wonder how can I debug this? There is no clear error message in SQL or Python. Thank you.
# all the imports
import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
app = Flask(__name__) # create the application instance :)
app.config.from_object(__name__) # load config from this file , flaskr.py
def init_db():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
print('create database successfully')
db.commit()
# there are other codes in between being ignored
#app.route('/', methods=['GET'])
def show_entries():
try:
db = get_db()
# cur = db.execute('select * from mouse_tracking')
check_table="SELECT name FROM sqlite_master WHERE name = 'mouse_tracking' and type = 'table'; "
print(check_table)
cur = db.execute(check_table)
entries = cur.fetchall()
print(type(entries))
print(entries)
except sqlite3.Error as e:
print("Database error: %s" % e)
except Exception as e:
print("Exception in _query: %s" % e)
return render_template('show_entries.html', entries=entries)
#app.route('/add', methods=['POST'])
def add_entry():
try:
print('posting the content')
db = get_db()
db.execute('insert into mouse_tracking (user_id, date, x, y, click) values (?, ?, ?, ?, ?)',
[request.form['user_id'], request.form['date'], request.form['x'], request.form['y']
, request.form['click']])
db.commit()
flash('New entry was successfully posted')
except sqlite3.Error as e:
print("Database error: %s" % e)
except Exception as e:
print("Exception in _query: %s" % e)
return redirect(url_for('show_entries'))
Here is the show_entries.html
{% extends "layout.html" %}
{% block body %}
{% if session.logged_in %}
<form action="{{ url_for('add_entry') }}" method=post class=add-entry>
<dl>
<dt>Title:
<dd><input type=text size=30 name=title>
<dt>Text:
<dd><textarea name=text rows=5 cols=40></textarea>
<dd><input type=submit value=Share>
</dl>
</form>
{% endif %}
<ul class=entries>
{% for entry in entries %}
<li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}
{% else %}
<li><em>Unbelievable. No entries here so far</em>
{% endfor %}
</ul>
{% endblock %}
here is the curl call
curl --location --request POST 'http://127.0.0.1:5000/add' \
--header 'Content-Type: application/json' \
--header 'Authorization: Basic cm9vdDpkZWZhdWx0' \
--data-raw '{
"user_id": "1",
"date": "2020-01-01",
"x": "720",
"y": "50",
"click": "0"
}'
Here is the schema.sql
create table if not exists mouse_tracking (
user_id integer not null,
date timestamp not null,
x integer not null,
y integer not null,
click integer not null
);

Consul-Template returns empty map?

Hi everyone,
I am trying to fetch a client token from approle auth method in vault. I have configured consul-template that it gets the role-id and the secret-id then, uses them to get the client_token at auth/approle/login end point. What is really weird is that first two steps are successfully executed and returned the data, however, getting the client_token is the struggle here. I analyzed the requests using wireshark and checked the response for the request that asks for the client_token, and it shows clearly the json result with the client_token included. But consul template does recognize the return and gives me this result:
{322a47b9-bf23-193d-8117-228637253fde 0 false map[] [] 0xc42001cf50 <nil>}.
The same way is used to request the secret-id but consul-template has successfully returned it and has recognized the json object. Isn't that weird?!
You can find the consul template below:
{{define "token" }}
{{ with secret "auth/approle/role/python-role/role-id" }}{{ $role:= (print "role_id= " .Data.role_id) }}
{{ with secret "auth/approle/role/python-role/secret-id" "role_name= python-role" }}{{ $secret:= (print "secret_id= " .Data.secret_id) }}
{{- with secret "auth/approle/login/" $role $secret -}}{{ . }}{{ end }}
{{ end }}
{{ end }}
{{ end }}
{{template "token"}}
Also, below is the wireshark trace that I used to check that the request went right:
Does anyone have an idea?
Thanks in advance.