Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.9K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
[AF] Swagger API [connexion] behind nginx(using gunicorn) using allow rules and ufw(Uncomplicated Firewall) rules.

From: https://gist.github.com/Morabaraba/06403358de009ede60e1d842c48100b7

So I have a wonderful Swagger API implemented in flask using connexion and sqlalchemy.

It is only a B2B(Business to Business) app. At the moment I have a `allow` rule for each client in `nginx` and use ufw on the cli:

```
ufw allow proto tcp from 42.42.42.42 to any port 1334
```

But instead of changing conf files and executing ufw commands manually, I would like to automate it.

I feel a simple `user_ip_address` table with a restful crud api will work:

```py
class user_ip_address(db.Model):
__tablename__ = 'user_ip_address'
user_id = db.Column(db.Integer)
ip_address = db.Column(db.String)
```

You call `/api/set-user-ip-address` with a `authorization` header identifying the user and the ip address in the `POST` body.

But at this point do I do a ugly:

```py
system.os('ufw allow proto tcp from {} to any port 1334'.format(ip))
```

and

```py
system.os('echo "allow {}" >> /etc/nginx/sites-enabled/h4ck3webapp.conf && service nginx relead'.format(ip))
```

While it might work it feels like a hack of hacks.

I'm now going to dive a bit deeper into nginx allow rules and uncomplicated firewall docs.

But I just need to bounce the idea. Coding in a bubble is not fun.



/r/flask
https://redd.it/6cvo4j
[AF]WTForms-JSON Form Not Posting Data

[WTForms-JSON docs here.](https://wtforms-json.readthedocs.io/en/latest/)

This has been a bug from hell I cannot wrap my head around.

I have a simple API handler that works perfectly fine from Postman JSON POSTs.

However when I plug the data into a web form the JSON is all empty. For example:

162.249.161.234 - - [23/May/2017 10:52:59] "GET /?customer=test+customer HTTP/1.1" 200 -
{'customer': None}

My Flask is as follows:

@app.route('/')
def index():
form = SubmitWorkorderForm.from_json(request.json)
print form.data
return render_template('submitworkorder.html', form = form)

@app.route('/submitworkorder', methods=['POST'])
def submitworkorder():
form = SubmitWorkorderForm.from_json(request.json)
print form.data
if form.validate_on_submit():
customer = form.customer.data
return jsonify({'customer' : customer })

And my HTML:

<div class="container">
<form class="form-inline">
{{ form.customer }}
{{ form.hidden_tag() }}

<input type="submit" value="go"/>
</form>
<br>
<div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div>
<div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div>

Lastly my JS:

$(document).ready(function() {
console.log("form Data:", $('form').serialize())
$.ajax({
type: "POST",
dataType: "json",
url : "/submitworkorder",
data : $('form').serialize(),
success: function (data) {
if (data.error) {
$('#errorAlert').text(data.error).show();
$('#successAlert').hide();
}
else {
$('#successAlert').text(data.customer + 'successfully created.').show();
$('#errorAlert').hide();
}
}
});

});

I have been working on this for the better part of 8 hours with no progress at all. Any help is appreciated.

/r/flask
https://redd.it/6cv8gw
I took my Django HyperText Coffee Pot Control Protocol Middleware implementation and released it as my first ever package on PyPi, would love to get some feedback and critique.

Here's the link to the package:
https://pypi.python.org/pypi/django-htcpcp/0.2.1

and here's a link to the github repo:
https://github.com/dashdanw/django-htcpcp

I tried to make it compatible for django 1.8-1.11 and python 2/3 and I would love to hear some feedback on code style and if it's actually working, or anything else I can do to make it a stable package.

This one is sort of a novelty but in the future I would like to start developing more libraries so any advice whatsoever, even if it may seem like overkill for a package this small, would be useful to me.

/r/django
https://redd.it/6cvgbr
Kernels in Docker Containers?

Hey, has anyone experimented with using docker containers as kernels? For example, you might spin up a docker container running a python3 kernel, but within the container you have some additional software resources that you can access with Python's subprocess calls.

/r/IPython
https://redd.it/6cx79u
Why is it named flask?

I'm literally filling up a flask currently and for the past month or so all I've been working on is the flask framework, and this question hit me. What's the significance?

/r/flask
https://redd.it/6cs1b2
Quick simple Django app

I'm new to Django.
I have experience with Web2PY.

I wondering if there is a pre-canned app framework that provides authentication and menu system.
I'm looking to just modify the model and view files to support a single table DB.

My requirements are minimal.
It's really a glorified web based spreadsheet.

/r/djangolearning
https://redd.it/6crgat
How do I handle %20 into spaces for a django filter for queries?

class SomeFilter(filters.FilterSet):
class Meta:
model = SomeModel
fields = {
'column1': '__all__',
'column2': '__all__'
}
So basically lets say I have a GET request using this filter like www.someAPI.com/?column2=something%20or%20Another

When I apply the filter above, it doesn't work because it's querying column 2 with %20 instead of spaces (which is what is in the sql database) how can I handle this so it queries correctly?

/r/django
https://redd.it/6czbac
Skater is a new Python library for model agnostic interpretation
https://github.com/datascienceinc/Skater

/r/pystats
https://redd.it/6cxmle
Gulp Js and Django

Im new using gulp and django I want to use both systems but don't know how. Right now my gulp is only setup to use and map javascript files only meaning instead of using the loadstatic command at the top of my html file I am using a meta file .

If anyone could provide an example or a good tutorial I would appreciate it. Thanks in advance.

/r/django
https://redd.it/6cxizt
Regex Hell: Is there a good way of combining multiple regex's into one?

Hi all,

I'm reimplementing the following regex I found in a paper. We're essentially trying to do name entity recognition for medical documents.

> import re
>
> """
> Reimplementation of regular expression for measurement extraction described in the
> paper found here: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4586346/
> """
>
x = "(\d+\.( )?\d+" + "|\d+( )?\.\d+" + "|\.\d+|\d+) *"
>
> by = "( )?(by|x)( )?"
>
> cm = "([\- ](mm|cm|millimeter(s)?|centimeter(s)?)(?![a-z/]))"
>
> x_cm = "(("+x+"*(to|\-)*" + cm + ")" + "|(" + x + cm + "))"
>
> xy_cm = "(("+x+cm+by+x+")" + \
> "|(" + x + by + x + cm + ")" + \
> "|(" + x + by + x + "))"
>
> xyz_cm = "(("+x+cm+by+x+cm+by+x+cm+")"+ \
> "|(" + x + by + x + by + x + cm +")" + \
> "|(" + x + by + x + by + x + "))"
>
> \# Final regular expression

> m = "((" + xyz_cm + ")" + \
> "|(" + xy_cm + ")" + \
> "|(" + x_cm + "))"

Whenever I run re.compiles(m) on the final expression, I'm getting a runtime error. Do you all have any suggestions on how I can cleanly break this up or where the error is? I'm trying to avoid having to use a context free grammar.

/r/Python
https://redd.it/6d1yg6
export as a normal Python session

Can we export the current session as if we had worked in the default Python shell? Here is what I mean. IPython session:

In [1]: li = [1, 2, 3]

In [2]: li
Out[2]: [1, 2, 3]

In [3]:

I want to paste it in a blog post, but it's too verbose (imagine that it's longer). I'd like to export it like this:

>>> li = [1,2,3]
>>> li
[1, 2, 3]
>>>

Is it possible?

/r/IPython
https://redd.it/6d2zi2
Save a django object getting another model instance as foreign key from a form

I am getting the URL tag from formnumber, but I would like to save the value in another model named ExpenseForecast. Any ideas?


def inputsexp(request, number):
formnumber = Projectsummary.objects.all().get(number=number)
form = ProjExpField(data=request.POST or None, instance=formnumber)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('app:test_forecast_data', kwargs={'number': number}))
context = {'form': form, 'formnumber': formnumber}
return render(request, 'projexpfield.html', context)

/r/django
https://redd.it/6d4pts