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
Sentry is pretty popular with Django because it's mentioned in the django docs, so I wanted to ask how you're all dealing with GDPR?

I'm a bit confused on what I need to do to be able to use sentry with Django so I don't get in trouble with ico because of gdpr.


They wrote a blog post here about: https://blog.sentry.io/2018/03/14/gdpr-sentry-and-you


But I'm still kinda confused after reading it.


And GDPR is supposed to be OPT IN instead of OPT OUT, right? But if you've already given your users cookies and sent their data to sentry the first moment they connect to your site, regardless if you have a banner on the top of the screen that says "You have to agree to use cookies if you want to use this website" but they haven't agreed to anything and they received those cookies before the banner showed up.


And I see that ICO is constantly handing out huge fees nonstop to companies all day long, they just don't run out of companies to fine. They really hit jackpot with this new law. You can see every company they've taken action against on ico's website.

/r/djangolearning
https://redd.it/8nm2oz
So hypothetically speaking, what should I do to learn python as much as possible before a job interview this Tuesday

Hypothetically speaking ofc

I have no previous experience with python, only SPSS, Excel and some R knowledge. No high level of python is needed, just the basics and maybe some more.

/r/Python
https://redd.it/8nno08
Moving from Java to Python?

So I'm a high school student with experience in Java up through the AP Computer Science level, and I want to learn Python in order to work with grad students at my local university. Where should I start?

/r/Python
https://redd.it/8no5bd
Getting data from a website?

Hi, currently I have some code using BeautifulSoup4 and TKinter to have a gui where it gets the HTML of a webpage I type in the GUI, but the problem is that the webpage I need has data loaded through javascript so BS4 is not getting that data. How would I be able to get that data? I've heard of selenium and PyQt4, but these both seem kind of difficult to install.

I need this program to work on a mac and windows, currently it works on a mac where I am developing it but would like to be able to move it to the windows computer when I am done and have an easy install. Please let me know what the best thing to do in my scenario is.

/r/Python
https://redd.it/8nnqj6
GUI Library help

Okay so I decided to make a browser as my next project but Ive heard that Tkinter isnt a good option and thats the GUI Library I am familiar with.. I was thinking something like KIVY I heard its good for a lot of things, but I have no idea how to do this at all to be honest

/r/Python
https://redd.it/8npgac
In Memory cacheing or not with Django

Hiya All

Been a long time lurker and would love and would love some info on people good at web technologies.

So use case. I'm lead developer on a BI team and for some quirk of history I'm rewriting a call center application for a global company hosted on AWS. Atm the app is a monolith of a frontend and DB backend, its legacy code built by someone for whom it was their first "programming project" so it's all spaghetti code and completely useless to try and refactor . but our operators are in Asia and America. I'm rebuilding the application to be a seperated backend and frontend, the backend will be written again in Django and atm I've built it as a REST API that can handle request for data. End users will use a front end to request sets of data to do with leads and property listings and then call up those leads.

The way im currently conceptualising this is we have our database backend and a REST API in django sitting in europe, then our end users working round the world make a request to it at the start of the session, get all of their leads and listings through the API then they're held in memory for the users session and they just post individual requests that we can deal with asynchronously \(celery \+ rabbitmq most likely\).

My question is, would it be better to go for an approach where an end user logs in, and receives all the listings and all the leads at the start of the session and holds them in memory then posts to the API with single entries, or is it better to make lots of individual requests to the backend based on user interaction \(I'd imagine i'd implement some sort of drop down menu in react\) which saves on a 5\-10 second load time \(just on my local machine, for someone in mexico requesting a server in europe load times would be longer\) . And if we are to hold this stuff in memory for an end user, what would be the normal approach for this?

/r/django
https://redd.it/8nko3j
Advice on making a better form submit button? (success_url)

With the django class based FormView, I'm not sure the simplest way to use the success_url.


I mean, I don't want the user to go to another "thank you" page.


I would like something else like for example, that the form vanishes and the thank you message takes it's place.


Or, a modal appears on top of it with the tank you message.


Or just a div gets displayed with a message beneath the form "your message is sent, thanks!".


Just some ideas, but I'm not sure how to accomplish this, I could most likely figure it out.. but I like learning shortcuts and I'm sure other people would like to know this as well. Good info to note down for later use, right?


I'm not using any SPA right now, I intent to learn to use react or vue later though but right now it's not in my toolset.


I know how to do everthing I said without Django btw.. it's with Django that I'm not sure how to go about this.

/r/djangolearning
https://redd.it/8nobv5
HELP - How to use application context inside the blueprint module model which reflects exsiting db

Hi,
I'm building a flask application. Here is the structure:

root_folder
|config.py
|manage.py
|app
|__init__.py
|mod_a
|mod_b
|__init__.py
|controller.py
|model.py
|view.py


in manage.py:

from app import create_app, db
from flask_script import Manager

app = create_app('production')
app.app_context().push()
manager = Manager(app)

@app.shell_context_processor
def make_shell_context():
return {
'db': db,
'User': app.auth.models_user.User,
}

if __name__ == '__main__':
manager.run()

in __init__.py:

bootstrap = Bootstrap()
db = SQLAlchemy()
migrate = Migrate()
bcrypt = Bcrypt()
authtoken = HTTPTokenAuth(scheme='Token')
api = Api()

def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
/////regist all the blueprint
db.init_app(app)
migrate.init_app(app, db)
bootstrap.init_app(app)
bcrypt.init_app(app)
api.init_app(app)
return app


Now I started to write code in models.py in mod_b, it needs to reflect existing database, I'm doing this:

from app import db
from sqlalchemy import MetaData

meta_db1 = MetaData()
meta_db1.reflect(db.get_engine(bind='my_db1'))
meta_db2 = MetaData()
meta_db2.reflect(db.get_engine(bind='my_db2'))

class Table1(db.Model):
__table__ = meta_db2.tables['table1']
__bind_key__ = 'my_db2'

def __repr__(self):
return self.__name__

class Table2(db.Model):
__table__ = meta_db1.tables['table2']
__bind_key__ = 'my_db1'

def __repr__(self):
return self.__name__
It always complains that Working outside of application context. Tried to import app, but in app there is no app_context()
What should I do to make sure models & reflection will have the correct application context? Thanks a lot for your help

/r/flask
https://redd.it/8nqsra
How to Prefetch_related with Formsets?

I'm getting too many duplicated queries in a UpdateView, one from each Formset instances and I don't know how to apply *prefetch\_related* with this case.

I've three models: Entry, that has multiple instances of Boxes, and each one has a FK to Material. So, in one Entry the user has multiples Boxes and each one has one Material associated. The problem is, when the user edits the Entry, for every Box he has, Django hits the DB looking for the material. How can I implement *prefetch\_related* \(or maybe *select\_related*?\) to solve this?

This is my code:

**models.py**

class Entry(models.Model):
....
# No Foreign keys here

class Box(models.Model):
....
material = models.ForeignKey('Material', on_delete=models.CASCADE)

class Material(models.Model:
....
# No Foreign keys here

**views.py**

class EntryUpdateView(UpdateView):
model = Entry
form_class = EntryForm

def get_context_data(self, **kwargs):
data = super(EntryUpdateView, self).get_context_data(**kwargs)
data['materials'] = Material.objects.all()
return data

def get(self, request, *args, **kwargs):
self.object = self.get_object()
form_class = self.get_form_class()
form = self.get_form(form_class)
box_form = BoxUpdateFormSet(instance=self.object)

return self.render_to_response(self.get_context_data(form=form, box_form=box_form))

**models.py**

class EntryForm(ModelForm):
class Meta:
model = Entry
fields = ...

class BoxForm(ModelForm):
class Meta:
model = Box
fields = ....

BoxUpdateFormSet = inlineformset_factory(Entry, Box, form=BoxForm, can_delete=True, extra=0)

/r/django
https://redd.it/8nqldy
This media is not supported in your browser
VIEW IN TELEGRAM
Visibility graph simulator built using Pyvisgraph

/r/Python
https://redd.it/8nsems
Developing a live-data fed dashboard. What is the best route to take?

Hello /r/python!

I am wanting to develop a dashboard that updates in real-time. (I'm playing around with RFID and want the numbers to adjust every time a card is scanned).

I've been researching Dashboards these past few days and did not realize how difficult it would be to decide which way to do this.


So if there are any Python devs here who has developed one of thse, which method did you take?
What I'm seeing now is:

* Vue.js + Django

* Flask

* Python script that feeds into a Django websocket

* Dash

* Plotly

* PyQt5

The most important aspect I need is data updating instantly. And obviously not anything incredibly difficult. I just want to see the data. Not make 110 awesome interactive graphs.

There are probably options I am forgetting. I love the Vue.js route but I am not really wanting to learn another language just yet as I don't feel I am where I want to be with Python.

Would anyone happen to have some advice?

Thanks!

/r/Python
https://redd.it/8nsf6k
[AF] Import issues with my project. Unsure how to approach.

I have a flask app that relies on web scraping to display data to the end user and let them download it. Right now, the various scrapers I have are sitting in the root level of the *myapp/* package/project so that they can write to app.db, a SQLite database.

Here is the current structure of the app:

my_app/
- app/
--- __init__.py
--- routes.py
--- models.py
--- templates/
--- static/
- scrapers/ (*note: my goal is create a folder like this)
--- scraper1
--- scraper2
--- scraper3
- config.py
- app.db
- scrape.py (*note: where my scraper currently is)


In the scrape.py file, I'm importing with the following import statement:

from app.models import db, table_name

My goal is to move scrape.py (and other scraping scripts) into a single directory where they can import **db** and **table_name** from app/models.py, but relative imports haven't worked for me.

Am I approaching this wrong?

/r/flask
https://redd.it/8nsv2a
What's up with all the dict key->attribute frameworks (python-box, dataclasses, namedtuple etc.)?

### Data Classes are a-comin'

So, now that we're getting [data classes](https://www.python.org/dev/peps/pep-0557/), we've finally got a concise and convenient way to avoid huge `__init__` methods full of `self.foo = foo`. That's great, that's fantastic, that's overdue. I'm sick of writing an entire `__init__` method for things that have like four attributes.

But it made me think -- why are there so many frameworks for taking things that would ordinarily be dictionaries and making their 'keys' available as attributes?

### The alternatives
####Namedtuple

`Namedtuple` kind of has a reason to exist other than as a key->attribute interface. Even with dataclasses, it provides the only super-easy framework to represent a datatype or small object:

Employee = namedtuple('Employee', ['id', 'name', 'salary'])

I like Namedtuple. I think that the syntax is a little silly because of that mandatory first argument, but that's just adds character. Namedtuple instances are immutable, too, and that's useful in its own way.

####Box
Box (`python-box` on pypi) is something I only just used for the first time today, and it's basically the same kind of thing, but more magic:

>>> bands = Box({
"My Awesome Band": {
"Albums": ["Foo, Vol 1.", "Bar Baz Blues"],
"Artists": ["Mr. Example", "John Doe"]
}
})

>>> print(bands.My_Awesome_Band.artists[0])

Mr. Example

It's super awesome and I immediately started using it to keep track of a deep, multi-layer dictionary I got courtesy of some JSON API. Having ['many']['layers']['of']['these']['selectors'] can get annoying.

Even dataclasses can't beat it: a `dict` in a dataclass is still dataclass.mydict['and']['then']['you']['come']['back']['here']. A `dict` in a `Box` has its keys exposed too.

### A clear trend

This entire situation reminds me of type hints, where despite the fact that Python will officially always be dynamically typed, the Python maintainers eventually sighed and admitted maybe there was some use for type annotations in programming, even if they were just so much syntactic sugar for Python itself.

Isn't it pretty apparent by this point that people like to access attributes with dots? Accessing them by ['string keys'] is fun and all, but it's ugly-looking and repetitive. Dots are cleaner. A dot-access class might lose case-sensitivity or might require you to use no special characters in keys or whatever, but those are just quibbles.

Would the community support adding something more like Box to the standard library? Should there be some kind of `collections.DottedDict`? Should we just admit, yeah, dots are nice, and while they're not the official syntax for dictionaries, they're available if you like 'em?


/r/Python
https://redd.it/8nx4sk
Newbie ForeignKey list problem

Hello,

Again I'm struggling with something quite simple.

I have two models. Products and ParoductCategory

*class* ProductCategory\(*models**.Mode*l\):
category\_name = models.CharField\(*max\_length*=40\)
slug = models.SlugField\(*max\_length*=40,* uniqu*e=True\)
*class* Product\(*models**.Mode*l\):
product\_name = models.CharField\(*max\_length*=255\)
product\_amount = models.IntegerField\(\)
updated = models.DateTimeField\(*auto\_now*=True\)
timestamp = models.DateTimeField\(*auto\_now\_add*=True\)
category = models.ForeignKey\('ProductCategory', *on\_delete*=models.CASCADE,* related\_nam*e='cat'\)
additional\_info = models.TextField\(*blank*=True\)

I would like to iterate over ProductCategory and create list of items in each productcategory model. Help me guys plz, I won't sleep if i won't understand where is my problem.

I' trying to use CBV, and I was playing with get\_context\_data method in view.

/r/djangolearning
https://redd.it/8nwr6z
I'd like to create a convenience app that works across all apps--where do I begin?

Vague title, I know. Lemme explain:
I'm trying to create a text translator that works across not only the browser, but on the desktop or any other app--as long as the text is 'highliteable', I want to be able to hold a key down and hover over the text and have a little pop-up appear and translate the text.

So what exactly am I looking for? A desktop app using tkinter? How do I sense that the mouse is hovering over text and that it's highlighted? Pyautogui?
All I know so far is that it'll involve a translation API.
What other libraries will be involved?


Feedback much appreciated!

/r/Python
https://redd.it/8nyn8l
When is a project due for a complete re-write?

I built a project that has been in production for about 4 years now and is integral to the daily operations of the business. Its original design and functionality was for a fairly narrow set of processes. Over the years as the company has grown, I've tacked on features, built in new work arounds, and expanded the project beyond its initial intent. It's all working fairly well, but I'm definitely seeing how it's aging. Right now I'm working on adding a new feature that, were the project designed differently/better initially, I wouldn't even have to write this new code \-\- the project would already be able to handle the new requirement.

Over the last year or two, I've often wondered if there's a valid case for "we need to rebuild this beast". Management is reluctant \(understandably\) since their business rides on the project working in its current state.

Any of you have experience on this front?

/r/django
https://redd.it/8nvw8c