#web-development
2 messages ยท Page 1 of 1 (latest)
:incoming_envelope: :ok_hand: applied warning to @plucky siren.
@lavish prism
https://github.com/shipagents/FastAPI-FullStack-Template
can you please review my repo guys?
please star if you like
hello
hiya!
umm.. I'm coming form DRF background.
Building API with flask, should I use the plugin?
Flask restful
well if you've never used flask perhaps you should familiarize yourself with it first
but yeah flask restful might be a good analogue to DRF
I've used flask for side project
I'm just thinking of going barebone flask for building API.
Just asking second opinion though
I usually build my APIs in barebone flask,
I've never had any compelling reasons not to.
I guess my advice would be to see if you can come up with a compelling reason to use more than just barebones flask, and if you can't, why bother?
don't use an extension just to use it, use it because you need a feature.
have u tried sanic
yea. it support async out of the box
right. yeah if you need async you might wanna look into some other frameworks.
I know @brave mantle loooves aiohttp
might be worth a look
Well it's all I had experience with
I tried kyoukai but it requires asphalt up the butt and at that point it's no longer a small framework
Never seen sanic
But my routes use route classes, not decorators, and aiohttp supports that
but the decorators are so pretty
Function is more important
I'm a romantic when it comes to programming :D
Haha
@prisma dawn for api's I don't use any module
I find it a lot easier just to use @app.route
And then add custom caching methods using decorators
Anyone use flask?
I've seen a few people using it
?
Treehouse
Treehouse actually helped me
Treehouse is well known for being kinda bunk
Bunk?
the best way I can put it is that their courses are broken
they're mostly fine but they all seem to have small problems that add up
True
(they're also really expensive)
Its cheap (for me at least)
I prefer more modern stuff, but that's me
Hey wats up, and yes, flask all the way!
aiohttp and friends
Btw, is flask a framework that employers look for?
python is very much moving towards asyncio
frameworks that refuse to support it will be left in the dust eventually
but I'm sure flask will at some point
I wanna learn django later on
True
it's worth noting that django is completely different and really requires you to do things "the django way"
Very true
if you're doing django properly then you even have it generate the project structure for you
Discord use Flask
Nice
Discord API is mainly Python
Ik
that could prove to be a bad move on Discord's part
You can even see Andrei using it in a dumb tweet lmao
I semi agree with gdude
Nah, that's not what I mean
i like flask so I'll stay with flask
Yeah
you keep making me feel stupid mister gdude :<
Dont worry joseph, gdude has a profile pic of a pony ๐
not the first time I've heard either of those things
Snd i have nothing
py!debug discord.utils.get(guild.members, name="Hasan Ahmad").avatar_url
Sorry gdude if i offend i, need to keep joseph motivated
it's the source code of google's swiffy tool
which doesn't exist anymore
it used to convert flash SWFs to HTML5
oh that sounds useful
I really need to learn js
flash has been deprecated for years now
flash is F U N
Theres this guy who says html is a programming lang
it literally has "markup language" in the name
Ikr
Sql is not a programming lang right?
Query lang
Im kinda new need to ask some questions
structured query language
Yep
Okay, ik its query lang
happy 21st october
I've worked with oauth
https://discord.report/ uses discord oauth2 for login
for a map, of all things
o
Theres this html code u can use to implement a disc server in a website
what if I don't want to know what it is mister gdude2002
then I'm still not telling you
since I'd be breaking the license that I wrote and added an exception for myself to
okay fair enough
xD
anyway the main thing you need to know is that discord oauth works and is also a pain in the ass to handle in a window
why not use Dithcord
because evie.codes wrote it and I have an aversion to her
plus the latest commit was in february
oh right, I forgot about her
Andrei's was 4 days ago kek
isn't she some super crazy feminist person?
I haven't interacted much but she was pretty hostile to me on the testers server for being a dude
she's crazy and minimods every discord server ever
borderline SJW, then..
even better
she makes youtube tutorials on discord bots
https://www.youtube.com/watch?v=Q03akWZkjZ8 comments disabled so much hATE
UPDATE FOR V11/V12: V11 and V12 deprecate the "sendMessage" function. But worry not, all you need to do is to change all instances of sendMessage() to just...
true
Im gnna change to django, guys, i think its time i grow up
:P
or we could just abandon Python completely and use Elixir Phoenix
It amuses me how many language specific servers I've been to where the staff prefer other languages
Lmfao
see
Can someone explain to me what the ```python
models.ForeignKey()
@grand badge Have you had a look at this? https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_one/
It's a foreign key relationship
Essentially it exists to refer to the primary key of a row in another table
thus associating this row with that one
I believe django generates a primary key for each model automatically, so that's what you'd be referring to
@brave mantle thanks!
No problem
@brave mantle do u use django mostly?
I use aiohttp mostly
oh yes i see wat u mean
I used to be a django guy
but then I wrote one system in flask and never felt compelled to ever use django again
i used to use flask but i think im gnna stick with django despite being more complex than flask
I used to think flask was great for smaller projects and django was great for bigger ones but now I just think people should use the microframeworks for any project and write whatever complexion they need from scratch, or piece it in by integrating optional modules.
true
for me, writing django is more fun than flask
and i feel that its easier for me in some ways
not trying to talk you out of django. it's a great system.
I used to use flak for most things
if you like it, you should do it!
flask is great
I use Phoenix more now but that's not Python ยฏ_(ใ)_/ยฏ
but after comparing ima go play with the pony
and the book Two Scoops of Django was very helpful, if you're into reading.
wat
I don\t think so.
okay
it's also not a super cheap book
so.. there are probably good free sources you can use instead.
I just really liked it for its writing style
was very lightweight and fun and easy to read.
it's not a django learning book though, it's best practices
so it's for people who know django and wanna write better django
haha
when u said expensive i thoght u meant 25 dollars or something
nope, it's expensive
you can probably get one for an older version of django and learn almost all the same lessons for a third of the price
but still
just something to consider for later
if you stick with it
its less in the uk but wow...
that's for django 1.5, a very old version indeed.
okay, gtg, was nice talking to ya
and also probably piracy?
and thanks korex for the link
seeya hasan
cya!
Whats the newest version?
like 1.11 or something
ok
I wouldnt buy it if I didnt have a steady income. tons of good free sources out there.
yeh true
Hey guys quick question, when trying to get this function to work where it takes a policy ID to pull information to render a template i get that the attribute has no get function.
https://pastebin.com/jteJViZM there is the paste with my code, i cannot figure out what is wrong its usually something really simple i cannot see or am overlooking as pointed out by devoid . any help would be greatly appreciated. the get function is supposed to grab the data from an ORM database with foreign keys.
hi
@torpid linden Please verify yourself as described in #352442727016693763
how do i get static files to work in Django?
the official django tutorial covers it, and it's a reaaally good tutorial
have you run through it?
i found it confusing
hi, not sure if this is the best place to ask, but i was wondering if anyone here has experience working bs4?
nvm, got it (:
Does anyone know any open source django projects that are good to learn from for a beginner?
got task was destroyed but pending
my idcheck function is taking long time to oerate but i have added await on it still it shuts the bot down
chrs=str(await idcheck(msg,0,message,client))
for file in repo.get_dir_contents('/'):
if file.name[-4:]=='.txt':
msg=urllib.request.urlopen(durl+file.name).read()
len1=len('{}'.format(msg).split('\\n')[0])
len2=len('{}'.format(msg).split('\\r\\n')[0])
if '{}.txt'.format(hwid)== file.path:
#print('{}.txt'.format(hwid)+'<==>'+file.path)
flag=1
return flag
elif len1<4:
msg1='{}'.format(msg).split('\\n')[1]
print(msg1)
if msg1==message.author.name:
flag=1
return flag
elif len2<7:
msg2='{}'.format(msg).split('\\r\\n')[1]
print(msg2)
if msg2==message.author.name:
flag=1
return flag
if flag==1:
break
#print('{}.txt'.format(hwid)+'<==>'+file.path)
return flag```
<@&391349088387334147>
Coroutines are not magic
You're using urllib to grab a url, that's your problem
You should be using aiohttp
okey wrkin on dat
tbh that problem is less of a user problem and more of an implementation problem, I'm starting to realise
Elaborate on that
The first message they see tells them to read the rules and type the verified command
your bot isn't smart enough, basically
Also your at everyone only made 3 people verify lmao
- It requires case-sensitivity
oh ty ty
- It doesn't prevent people from assigning other roles when not verified
- It makes us clean up incorrectly-formed messages (and chat) manually
I might just make a custom bot for all this
instead of editing PyButt every time lmao
lol what
Not sure if this should go here, but when I'm using selenium webdriver with the --headless flag, I still get a console log window open. Is there any way to hide this?
save it as a .pyw file and see if that does the trick. on windows anyway
headless only prevents the browser window
Tried it, but it seems that this window's the selenium log or smth. Looks like the python window is seperate
hm. right
have you tried with firefox instead of chrome as the driver? might be the same, iunno.
I'll have a look when I get home, thanks
the far more complicated solution in windows would be to somehow get chromedriver to run as a service
but I have no idea how to make that play nice with selenium
there seems to be some github packages intended to make chromedriver a service for use with the java version of selenium and with seleniumgrid
but nothing for use with python
that I can find, anyway
interesting problem, though
how do i send emails in django???
i went through it, and i got smtp auth error
so your password is wrong
it was right
nope
u sure??
yep
that's what the error means, after all
although knowing most people around here, you're probably using a mail service with 2-factor
yep
yeah so you can't use your normal password
you have to generate an app password because 2-factor only works in the browser and gmail apps
sooooooo how do i do that?????????
well, you'll have to do that with your mail provider
that has nothing to do with anything
ik..
Does anyone use Flask here? =x
Okok, good to know. I will definitely have questions tomorrow ๐
home now
I just had this question I already asked on the github: https://github.com/noirbizarre/flask-restplus/issues/372
More focused on Flask-Restplus/Restful
I'm struggling in Flask-RestPlus with the following marshalling:
'articles': fields.List(fields.Nested(article, attribute=lambda x: x.articles)),
My Request table has articles = relationship("RequestArticle", cascade="all, delete-orphan"),
And RequestArticles has article_id = db.Column(db.Integer, db.ForeignKey("article.id"), primary_key=True)
I want to get in 'articles' the full detail of article.
Finally having something working
'articles': fields.List(fields.Nested(article), attribute=lambda x: x.articles[0].article)
but it only gets the first then
How can it not only be the first? should be obvious I guess since it's a list, but can't find a way
This is not working:
'articles': fields.List(fields.Nested(article, attribute=lambda x: x.article), attribute=lambda x: x.articles)
I get: TypeError: hasattr(): attribute name must be string
Anyone doing flask here? ๐

You are asking in a channel that has 16 people online.....
@iron acorn So is everybody using Django?
I think more so than people using flask
AFAIK more django resources on web than flask
Most people use flask or aiohttp here
I don't use flask, @kind steppe is always recommending it though so he might have an idea
@brave mantle Ah good to hear ๐
But @kind steppe is not in the #web-development channel =x
No, he is, owns the server
hello yes
I have used flask but I've never used what you are talking ahout
Also I don't really like flask anymore lol
I use something non Python lol, but Flask is your best Python webserver
@kind steppe Really? ๐ฎ
Django seems a lot more popular
And Flask is confusing to me.. Note I have never been very involved in back end development, I'm a front end dev.
Flask makes you write more boilerplate than django
The companies love django because it's standardized and can be documented easily
but it's a bit of a behemoth
flask, on the other hand, isn't really that opinionated about how you do things
My company chose Flask ๐ฌ
The problem is that I'm front end oriented, and in my company, no one knows really Flask โค
Then your company is one of the better ones lol
yeah, that's the problem
there's a lot of backend to write
flask won't do your database stuff for you for example, you'll have to do that yourself
django comes with an ORM
I asked a question on the github of restplus(because that's what we use), I don't get why we have to write most twice marshalling and parsing...
I use sqlAlchemy
SQLAlchemy is pretty great
Pair it with alembic and, hey, there's your migrations
I also use alembic
tbh, they chose all the stack, I am unexperienced on back end stuff and no one knows around me how it should be used (international company)
I mean I know what the words mean, but not the context
reffering to?
you're marshalling/parsing something
what's that something?
if you say "data" I'mma slap you
:P
right okay, so you have a schema and that's used to fill a dict, given some data
So you'd say it is different then. But on my end points I can write @expect(some_schema), so I define already what I want in entry, why do I have redefine aaaall the keys again? (because on the parsing step, you have to specify each key you want)
system not smart enough?
That's not a flask thing anyway
at least, not that I know of
I'm confused as to why you need those
Even flask-restplus suggest to use marshmallow for marshalling
Is marshalling a common word for back end python?
Not really
ok
OK, so let me get this straight
so if should come from rest*
you're defining a schema
and that schema is used to validate incoming data via the rest api
to ensure it has the correct params
right?
in and out
Ok, so the returned data as well
it sounds like it would be trivial to write a middleware and decorator for that
I use @expect() and @marshall_with(), which defines the model out
Like, let's say you have a middleware
You have it inspect incoming requests, and also inspect returned data
Actually no, the decorator can do all of that
so you have your decorator defined like, I dunno
def validate(func, **kwargs):
I'm not sure how complicated your schema are, but assuming you're just looking at keys and values in the request, it should be easy
@validate(key=int)
def get():
return ...
looks like that. I think it already takes care of the validation (you can specify many things: require, type, min-max, etc)
but I just don't get why I define a schema and set it as input AND have to rewrite all the keys inside. What's the point to 'expect' something in then? Oo
It just sounds like your schema library isn't smart enough honestly
I mean either I misuderstand something, or the design is wrong. I guess it is the first assumption, but still can't find anyone explaining this to me.
You'd probably have to ask whoever wrote the library
..and then we're back where we started I guess
So what do people use above Flask usually?
Above?
like nodejs would come with express. Are there any popular usage of libraries above Flask?
I bet, same for node ^^
what about rest libraries?
the biggest thing I don't like about Flask is that the community is very slim...
compare to Django
well I dunno why you even need a REST library in the first place honestly
flask is minimal enough that making your endpoints is already easy
ah, :P
I added my self
good
So are you saying i cant make a script in the models.py to add json data to the database?
uh. sure you can.
but
basically inside models.py you're defining the generic model, so you have to do it in a generic way.
let's say you have a json file that has the age of all the users
you could set an age property inside models.py that goes into that json file and looks up the age based on the users name or something.
the key is to do it in such a way that it will work for every instance of that model
The data comes from an api of another site
yeah. well you could have a property in your model that looks up some information in an api.
I made a def function that does
Im just not sure how to take the return data and put it into each field of the model
okay. so you have a function inside the model that does what you want it to do?
It gets the json data ges
basically you can just treat that function as a normal attribute then.
Yes*
for example
if you have
class User(models.model):
def age(self):
# call some API and get the age
age = api.get_age()
return age
say you have this
now all your users will basically have an age property that you can just access like any other field.
so in your template you can simply do {{user.age}}
huh, didn't know django could do that without a @property
all functions inside of models.Model objects are essentially treated as a @property
at least.. if I recall correctly. it's been forever since I wrote actual django but I'm looking at some old code now and I don't have a @property decorator on any of my functions.
haha
but @native tide , to be clear, this doesn't actually store the return value of age() in the database. the database will only ever really have a reference to that function.
Thanks man
I never read those :(
lol rip
youre verified so you agreed to them rules tho
The verify me command wasn't there IIRC
!info @brittle copper
โฏ User Information
ID: 361708843425726474
Profile: @brittle copper
Created: 3 months ago (2017-09-25T03:01:48)
โฏ Member Information
Joined: 2 days ago (2017-12-28T12:18:35.671478)
Roles: Verified, Web Development
โฏ Activity
Last Message: 2 minutes ago (2017-12-30T14:41:48.457000)
First Message: 2 days ago (2017-12-28T12:20:02.137000)
And I still can't see the verify me command there
Joined: 2 days ago (2017-12-28T12:18:35.671478)
yeah when you verify you get removed from the checkpoint channel
well you cant see the #352442727016693763 channel yeah
are you a hackerman
Yeah that is the problem
I just copied the command without doing anything you ask me to do
understandable
lmao
I didn't even read the text after the command xD
understandable
Wouldn't it be awesome if django had the ajax ability with it
So we could write our ajax too with python :(
@brave mantle what was that python for web thing you were showing?
They've been working on webassembly compiling for python, but webassembly isn't ready for that kind of use yet
You can't really interact with the DOM with it yet
no there was the other thing
There are a few JS transpilers around or JS-implemented VMs
I can't remember off the top of my head
easy to find though
Brython
that was it
@brittle copper you could use this http://brython.info/
from browser import document, ajax
url = "http://api.open-notify.org/iss-now.json"
msg = "Position of the International Space Station at {}: {}"
def complete(request):
import json
import datetime
data = json.loads(request.responseText)
position = data['iss_position']
ts = data['timestamp']
now = datetime.datetime.fromtimestamp(ts)
document["zone10"].text = msg.format(now, position)
@document['button10'].bind('click')
def click(event):
req = ajax.ajax()
req.open('GET', url, True)
req.bind('complete', complete)
document["zone10"].text = "waiting..."
req.send()
This looks promising
It's pretty nice from what I've seen
Yeah, before trying to learn js I'll deeply look into this, thanks alot
@deep cave no i didnt get it working bro
I did figure out from further reading the documentation that i need to use a costume django-admin command but i keep getting a error when i run the script
class Title(models.Model):
title_text = models.CharField(max_length=50, null=True)
title_url = models.CharField(max_length=100, null=True)
def __str__(self):
return self.title_text
class Entry(models.Model):
entry_title = models.ForeignKey(Title, on_delete=models.CASCADE)
entry_text = models.CharField(max_length=2500, null=True, blank=True)
entry_author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
entry_date = models.CharField(max_length=20, null=True, blank=True)
entry_points = models.IntegerField(null=True, blank=True)
entry_id = models.CharField(max_length=10, null=True, blank=True)
entry_readability = models.BooleanField(default=True)
def __str__(self):
return self.entry_text```
How do I get all the Entrys' titles?
Not all the titles, I need them in an order so I need to get all the Entrys' titles and use them like that
Im making a script to set up the data base when the site is first deployed
Would it be slow to request the json data one at a time then save
Would it be better to req tell the needed amount is met then save them?
Also when i first deploy the site it will be a lot
no, that sounds like it would be the same. can't you request all the data in one request instead of lots of little ones?
it's the network traffic you wanna watch out for, that's the real killer. doing 10000 webrequests is bad. doing 1 webrequest for 10000 things is ideal. likewise, you don't wanna do 10000 insert statements to the database, you wanna insert 10000 things in one go.
all the stuff you do in python is usually very fast
but making network requests is sloooow.
and if you absolutely have to make thousands of requests, you probably wanna look into threading or something so you can do multiple near-simultaneous ones instead of waiting for each one before starting the next.
Yes i see
I will just look for a better way to get wha i need
What*
A single req per item just wont work but there service only allows it that way
but with all that said - don't optimize before you test.
if it's fast enough already, all of this is pointless.
first make sure it's actually slow, then fix it.
premature optimization is the bane of many talented programmers.
maybe the API is extraordinarily fast, maybe you don't have to fetch as much data as you think, etc. learn to profile it.
@deep cave i found a much better service that allows multiple items to be called with one req thanks so much for your advice bro
good!
hey, no problem. that's what we're here for.
try to do the same when you spit the data into the database, too
This is my first site that im putting up for commercial purposes
when inserting tons of data, there are techniques. you may wanna read up on it a bit.
common mistakes people make are to connect to the database more than once, to insert the items one line at a time, or to try to insert everything in one huge chunk.
what you want to do is connect one time, then insert batches of data at a time, verify it's working, and then commit.
you might want to do a bit of reading to find the best approach
Do you have any example code you have a link to so that i may see?
the approach differs from database to database.
Or where to find it in the docs
just google "inserting large amounts of data into postgresql" or whatever db you're using.
what db are you using? just out of curiosity?
MySQL cuss dreamhost offers ulimited space for it
Is there a way to save data in the way your talking about using a model or will i have to use raw sql?
some approaches here
I've never really worked with mysql but building a multi-row insert is usually a good approach
Django doc said to avoid raw sql as much as possible
oh you're working with django. I see.
no, I think you have to use raw SQL for this kind of thing.
the django ORM is not suitable for bulk operations afaik
although it's possible if you go ask #django on freenode or something they will have a suggestion
there is this bulk_create() method
but.. iunno man
again it depends on the amount of data
I would have just written some SQL for this
it looks like if you absolutely must, you could probably use a list comprehension with that bulk_create() method
to insert your data
I just have never delt with it
Entry.objects.bulk_create([Entry(headline=x) for x in headlines]) would presumably work if you had a ton of headlines in a list
but I don't know how performant it will be
so you might wanna test it if you wanna keep it in the family - and then do some profiling to see how long it takes.
but if it's super slow, pure SQL will probably be the way to go.
I will test and see thanks
I'm assuming you understand listcomps
feel free to say if you don't, I'm happy to explain them
it's like a shorthand for building a list. it's very powerful and you probably should google and read a bit
but basically
nums = [1, 2, 3]
# this code
strings = [str(x) for x in nums]
print(strings) # => ["1", "2", "3"]
# is the same as this
strings = []
for x in nums:
strings.append(str(x))
print(strings) # => ["1", "2", "3"]
Whats diffrence does it make one way over the other then?
python considers them the same - but basically the former method can be very succinct and elegant if wielded responsibly
you can use the second approach if you prefer it
Entry.objects.bulk_create([Entry(headline=x) for x in headlines])
this is a good example. the second approach would have looked like this:
entries = []
for x in headlines:
entries.append(Entry(headline=x))
Entry.objects.bulk_create(entries)
I prefer the first
or you can strike a nice balance between them and go for
entries = [Entry(headline=x) for x in headlines]
Entry.objects.bulk_create(entries)
anyway it's all style
obviously in your case you'd replace the Entry constructor with whatever model you wanna create, but it should be easy enough to adapt.
good luck
Hey guys
I am having difficulties to find my way around something or the right way to do it.
I am using Flask-RestPlus (same as RestFul)
I would like a marshalling such as follow:
'articles': fields.List(fields.Nested(article), attribute=lambda x: x.articles[0].article),
The problem is this [0], it is a list , I should not have to precise any index
But I can't figure out how to say I want the current object articles list and inside this relashionship I want the article relashionship.
I can provide more information if required, I just don't wanna spam of information๐ค
lambda: http://flask-restplus.readthedocs.io/en/stable/marshalling.html#renaming-attributes
list & nested: http://flask-restplus.readthedocs.io/en/stable/marshalling.html#list-field
If that makes more sense to some one here than to me...
Still on it ๐
:\
You might have better luck posting in #help-falafel? Afaik you don't need any self-roles to see questions
@mild bridge But Flask is really web dev, I'm afraid they won't like that.
Uhm, quick question: https://hastebin.com/heribukine.vbs is this a healthy looking view in django?
@signal karma
๐ฎ
first of all let me just say that I don't really see the point in Flask-RestPlus at all. just write the whole thing from scratch, this just overcomplicates it. :/
secondly, I think the key to solving your problem is to use a real function instead of a lambda
I think it is because it carries swagger
but in order to help you with that, I need you to clarify what you mean by "the current object"
current how?
can I maybe see some more code?
hm, in an end point, I return an object. This is the 'current object'.
Sure
article_full = namespace.model('ArticleFull', {
'id': fields.Integer(required=True),
'title': fields.String(required=True),
'description': fields.String(required=True),
'image': fields.String(required=True),
'brand': fields.String(required=True),
# TODO: Fix index location to user making the req
'price': fields.Float(required=True, attribute=lambda x: list(filter(lambda y: y.location_id == 1, x.prices))[0].price),
'category_id': fields.Integer(required=True),
})
@namespace.route('/')
class ArticleListAPI(SecuredResource):
"""Articles REST end points"""
@staticmethod
@namespace.marshal_list_with(article_full, envelope='articles')
def get():
return Article.query.all()
I have 2 lambdas
this is one of them
Does that make more sens? =x
sure, you always use a lambda with filter
or. well, almost always.,
I can't speak to whether or not it's correct without seeing the rest of the code, but I take it this one works for you then?
it does, just it should be dynamic on the user's location
okay
instead of y.location_id == 1
but I guess I can write whatever inside, since it seems it is only evaluated on return
When called
so, would you know how to write a real function that returns the correct price?
taking in some sort of user location identifier as an argument?
it seems like a much simpler way to go about this
That one thing I need to figure out, how to know who is making the request for thiskind of cases
and also to restrict API to users rights
and attribute takes any callable that returns a value
so you can just put a regular function call in there
instead of this gross lambda stuff
I could do that for the location. I'll probably do that, but not for the rights
no, that's true, you'd probably want to restrict users at a higher level and never execute this if they don't auth
okok good to know, I'll avoid lambdas^^
you don't have to avoid lambdas -- but it's a good place to start if you're not sure why this doesn't work.
i thought to build a decorator for that, but I still need user info
right
I thought of using JWT or redis cache
I mean I don't see how you're gonna do any of this without knowing who the user is
exactly ^^
yeah JWT is one approach I guess
but I guess you should start with that. figure out who the user is. then auth the user. and then write functions to use that userdata to fetch the right price or article or whatever it is you wanna fetch
then stick those functions in the marshalling attributes
problem solved
that make sense?
ok
yes it does, it's more clear to hear it^^
Actually the problem I am trying to solve right now is how to get a SQLAlchemy relashionship many-many with the extra data inside the linked table.
I guess it should come from the table definition...
what's the database
sqlalchemy is just how you access the database, and generally speaking the relationships are defined in the database itself.
class Request(db.Model):
"""Model for Request."""
__tablename__ = 'request'
id = db.Column(db.Integer, primary_key=True)
# [...]
articles = relationship("Article", secondary="request_articles")
so you're asking the wrong question.
I mean, don't get me wrong, SQLAlchemy does have mechanisms for many-to-many
but first you need to look at your actual database
and see if it even supports it
sure. okay. mysql.
which of course has all kinds of relationships
an example here
this should work fine in SQLA -> MySQL
or at least something like it
also some good examples here
Ok. I personally followed the sqlalchemy doc on Association Object: http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#association-object
I just get the Article information, not the extra data from the middle table
request <- request_article(extra data) -> article
but my relationship is
articles = relationship("Article", secondary="request_articles")
that doesn't seem to match how they've done it in the documentation you linked.
let's see some more of your code for how you make that relationship
class Request(db.Model):
"""Model for Request."""
__tablename__ = 'request'
id = db.Column(db.Integer, primary_key=True)
# [...]
location_id = db.Column(db.Integer, db.ForeignKey("location.id"), nullable=False)
articles = relationship("Article", secondary="request_articles")
class RequestArticle(db.Model):
"""Model for Request Article."""
__tablename__ = 'request_articles'
id = db.Column(db.Integer, primary_key=True)
request_id = db.Column(db.Integer, db.ForeignKey("request.id"))
article_id = db.Column(db.Integer, db.ForeignKey("article.id"))
state_id = db.Column(db.Integer, db.ForeignKey("state.id"), nullable=False)
quantity = db.Column(db.Integer, nullable=False)
article = relationship('Article')
class Article(db.Model):
"""Model for Article."""
__tablename__ = 'article'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255), nullable=False)
description = db.Column(db.Text)
image = db.Column(db.String(255))
brand = db.Column(db.String(255), nullable=False)
category_id = db.Column(db.Integer, db.ForeignKey("category.id"), nullable=False)
prices = relationship("ArticlePrice", cascade="all, delete-orphan")
You have it all here guess
Does that clear it up ? =x
yes, gimme a minute to read.
right. but you wanted bidirectional relationships, right?
so in the documentation you linked, they show an example using back_populates
did you try that?
there's also no use of secondary
not really. I have a table of articles to show it in the store. I have a list a requests to which are attached articles, and here I need the article details.
and I'm not sure, but something tells me that perhaps the variable names child, children and parents are not arbitrary but may infact be required to tell the classes about the relationships
But articles themselves do not need to know which request they are attached to, that's why I didn't write a backref
I use the secondary to avoid returning the request_article table(when I request all Requests), I want the article full information, on the first level. But this way, I miss the extra data =/
That's why I had a lambda in the first place, I wanted the article info not just its id(from request_articles).
I mean in the docs, they basically handle all that stuff after the def, but you sound like you want to just map the property of the one class to the other.
I mean, the value of this association stuff is in this code example
# iterate through child objects via association, including association
# attributes
for assoc in p.children:
print(assoc.extra_data)
print(assoc.child)
And I would like to have these two merged
on return
Maybe it is not possible =x
But I am a front-end dev originally, and I'd ask to my backend dev to return it as such.
it's probably possible - but I'm not sure I understand why
if you have these relationships intact, you have access to everything
why do you need to merge everything
Because I want to treat it as one thing, not as extra and original data
I get that but you can still merge those two things before you return them to the API caller
this is back end logic, the client should not have to be aware of what is extra
the problem is that you're trying to do that in the ORM class definitions.
that's not necessary
Maybe I should...
I was worried of treating all the records before return the values, but I should use paging anyways...
I wanted it to be automated from there ๐
again - you can just make a function, feed it both of the datas, merge them in the function and return the merged dataset, and then feed that function to attribute
just to keep it simple.
yeah, like you're doing with the lambdas
def merge_data(data1, data2):
return data1 + data2 # it's probably not this easy but I'll let you figure this part out
# ...
'price': fields.Float(required=True, attribute=merge_data(data, extra_data)),
something like that
not quite like that, probably, but you get the idea.
I've never really worked with flask-restful, and I almost never use sqlalchemy either so this may not be the optimal or intended solution
but I think it'll work, and really, that's the important part.
seems close to what I had, I got lost over trying I guess
haha
@brittle copper I guess it looks healthy, but it desperately needs blocks and comments for readability.
it looks cramped, currently.
Nice, I was worried about the length because I read something like don't write too long view function; if the only problem is that it lacks comment, I can always add some :D
blank lines and comments. yeah. it'll be longer, but it will be split into chunks which will make it far more readable.
right now it does look long
but only because the whole thing is just one big chunk
it's kinda like writing a normal english article or something, you need paragraphs, headlines, subheaders. nobody wants to read a wall of text.
I tried to follow pep8
PEP8 says something like "use blank lines (sparingly) to indicate logical sections inside functions"
Hmm, PyCharm didn't warn me, damn :D
it also has a section on block comments
# this is where the fudge gets made
go_around_corner()
for step in factory.road:
take_step(step)
fudge = make_fudge()
# reformat and return
refudgify(fudge)
return fudge
this kind of thing is great for readability
although just make sure your block comments aren't too obvious
I probably wouldn't have written that last one
the point of the comments is to let the reader skim your code
and see what a section of code does without having to read any code
Yeah should add comments, some does look like as if it doesn't make sense without any context
and lastly - pycharm is great for helping you maintain your PEP8 compatability
but
PEP8 is short
read it
at some point, at least, in your python career
My 30 days of python carrier xD
you don't have to read it today, but it's quite pleasant reading
it's not too bogged down in technicalities
gives plenty of examples
and a lot of the stuff in there is just really smart stuff you can apply to any language
python is, after all, quite famous for its emphasis on readability and ease of use
and PEP8 is one of the reasons it has earned that reputation
it's a honking good document
Alright I'm on a train rn so I have nothing better to read :D
cool
And thanks again
no problem.
I receive this error : TypeError: int() argument must be a string, a bytes-like object or a number, not 'Integer'
sending this:
{
"id": 2,
"articles": [{ "id": 1, "quantity": 2, "state_id": 2 }, { "id": 1, "quantity": 1, "state_id": 3 }]
}
with this python:
request = namespace.model('Request', {
'id': fields.Integer(required=True),
'by_user_id': fields.Integer(required=True),
'for_user_id': fields.Integer(required=True),
'reason': fields.String(required=True),
'location_id': fields.Integer(required=True),
'articles': fields.List(fields.Nested(cart_article)),
})
@namespace.route('/')
class RequestsListAPI(SecuredResource):
"""Requests REST end points"""
@namespace.expect(request)
@namespace.marshal_with(request_full)
def put(self):
parser = reqparse.RequestParser()
parser.add_argument('id', required=True, type=int)
parser.add_argument('articles', required=True, type=cart_article, action='append')
args = parser.parse_args()
I have no idea where is comes from, I send only ints and it says it should be a string... my model only takes integers too... Note I get this error even commenting the whole function. I guess it must come from the @expect.
Well, look at the traceback yourself then
You should see the file you wrote code in somewhere
it is the lib --
It'll give you the exact line
File "C:\HOMEWARE\Anaconda3-Windows-x86_64\lib\site-packages\flask_restplus\fields.py", line 394, in format
return int(value)
last log
Most people don't know how to read a traceback here :P
it doesn't make sense since as I said my model takes int and I send ints.
I think I can easily wager what the problem is
I guess it makes one more
But I don't have the full traceback
but if the error was clear in the first place...
No, I think it's pretty clear
You're doing type=int in one of your calls to add_argument
That's my first guess
OK, you have a decorator of your own there, are you sure that decorator is correct?
No, app/core/decorators.py
uh
It's in the traceback
๐ฌ

Actually it's not my code, worked well so far, I don't even know what it does exactly =/
You're using it though
yep
Read the code, that might help you figure out what it does :P
yep will do thanks ;P
It is supposed to check authorization, that's all I know
it should not touch the data
and it doesn't
even all the operations inside the function works fine, I just get an "Internal Server Error" on the client side
Try deleting the last bits of codes that gave the error and try another approach for the same thing you are trying to do maybe? @signal karma
there's always an error associated with one of those internal server errors
set up logging for flask and check the log file, you'll see something
Guys, how do we change BooleanField in django?
Class.objects.get(pk=165).bool_fiel = False doesn't seem to work
And yes I do save it afterwards
I've tried ^= False and = not Class.objects.get(pk=165).bool_fiel too
why are you trying to do that
it's a field, you're supposed to spit it out into a form. it represents the field. like.. a checkbox. it's not a boolean.
it doesn't really have a value. it can have a default value. the form is what has the value, after the user submits it.
I can change every other field without needing a form, why can't I do it with this?
but why would you want to
I feel like you're using form fields in a weird way if you're changing them
If a user wants to change his post from visible to not visible when he presses to button it takes him to www.page.com/delete/post_pk
def togglevis(request, entry_pk):
referer = request.META.get('HTTP_REFERER')
if User.objects.get(username=request.user.get_username()) == Entry.objects.get(pk=entry_pk).entry_author:
Entry.objects.get(pk=entry_pk).entry_readability ^= False
Entry.objects.get(pk=entry_pk).save()
return HttpResponseRedirect(referer)
else:
raise Http404```
Form fields? I'm talking about model fields
class Entry(models.Model):
entry_title = models.ForeignKey(Title, on_delete=models.CASCADE)
entry_text = models.CharField(max_length=2500, null=True, blank=True)
entry_author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
entry_date = models.CharField(max_length=20, null=True, blank=True)
entry_points = models.IntegerField(default=0, null=True, blank=True)
entry_readability = models.BooleanField(default=True)
def __str__(self):
return self.entry_text```
right, that makes more sense.
:D
(they're both called BooleanField, fucking django)
Damn
btw I hate django
right so you're really trying to change entry_readability in this case?
After python @register.filter(name="replacer") def messagetolink(text): split = text.split('`') even, odd = split[0::2], split[1::2] return format_html_join('', '{}<a href="' + site_name + '{}">{}</a>', ((a, ("_".join(b.split())), b) for a, b in itertools.zip_longest(even, odd, fillvalue=''))) I hate it too
Exactly
oh god, that's hideous.
There is no way to make a string permanently safe apparently
Soo, @deep cave how can I toggle the readability?
my eyes!
I'm not really sure. what you were doing (the =, not the ^=) should have worked.
that's how I would have done it, anyway
but.. uh.. you can specify the optional arguments in the .save() method maybe
iunno if it will help but it's a thing to try
wdym
you can do like
Entry.objects.get(pk=entry_pk).entry_readability = False
Entry.objects.get(pk=entry_pk).save(['entry_readability'])
and see if it likes that better
Lemme try
it shouldn't matter, but
I think it does an UPDATE instead of an INSERT when you specify
there's a force_update keyword argument you can do, too
it's possible your save is doing INSERTs instead and creating new rows
but you want to update existing rows
omg
lol, I guess it inserted a duplicate
naw, just remove the duplicate manually
The DB should have rejected it
and try again but this time with the force_update keyword argument
and yeah the DB should have rejected it. :/
again - did I mention I hated django?
no. I like flask.
Fair do's
I used django as my first ever webframework
so I kinda know it a little bit
but it was a pain in the ass
discovering flask was like a religious experience after having worked with django
sadly I still have to maintain a few django apps
you removed the duplicate and tried with force_update?
Yeah
When I toggle it from admin panel it works as expected, the posts doesn't show up in their link but I can't do it from a damn view
have you made sure that your Entry.objects.get(pk=entry_pk) actually gets an object that you can use?
I have another view with url www.webpage.com/entry/entry_pk which shows the related entry
right.
try this thing again but this time specify the argument name
Entry.objects.get(pk=entry_pk).entry_readability = False
Entry.objects.get(pk=entry_pk).save(update_fields=['entry_readability'])
cause.. I can't find the .save documentation so I'm not really sure about the order, can't confirm if update_fields is actually the first positional
Yeah this doesn't work either
I'm just gonna use CharField as BooleanField by giving it either 1 or 0
Thank you for your help anyway :D
I mean, if it works from the admin panel I suppose you could just try to figure out how it's done there
the admin panel is after all just code in your project
but.. yeah I guess a charfield will do the job
I've done worse hacks in my own django projects :(
and to be clear - I'm sure if you go on freenode #django and ask, they'll tell you that there's a perfectly reasonable justification for this behavior
and that if you only do this and this and this and this it will work fine
because that's django in a nutshell
but I'm afraid I'm too shit at django to tell you what it is.
def togglevis(request, entry_pk):
referer = request.META.get('HTTP_REFERER')
entry = Entry.objects.get(pk=entry_pk)
if User.objects.get(username=request.user.get_username()) == Entry.objects.get(pk=entry_pk).entry_author:
entry.entry_readability = False
entry.save()
return HttpResponseRedirect(referer)
else:
raise Http404```
django to me is just chock full of these "why the fuck is it doing this" situations and then if you ask the django guys they're like "oh yeah that's a feature not a bug"
Apparently this works
wait, how is that different
oh.. maybe because it's just one get
instead of two!
maybe by getting it twice you're undoing your previous changes
Apparently my former try was getting the object second time before saving it
that's pretty common, though
yeah, I guess it makes sense
Yeah, I can't believe I wasted 30 mins for this
sure you can
I just didn't want to assign the object to a variable since I wasn't gonna use it again and again
30 minutes isn't even that bad
Oh god I don't want to end up being a programmer xD
you're already a programmer
Damn
cause it's friday night and you just spent half an hour on a django problem.
But the hardest thing I've ever done so far was python @register.filter(name="replacer") def messagetolink(text): split = text.split('`') even, odd = split[0::2], split[1::2] return format_html_join('', '{}<a href="' + site_name + '{}">{}</a>', ((a, ("_".join(b.split())), b) for a, b in itertools.zip_longest(even, odd, fillvalue='')))
This
non programmers don't do that
And I didn't even do that, couldn't, someone else did it for me
well, that's almost ugly on purpose
How else can you do that?
just do it with more lines of code, it'll immediately be cleaner and more readable.
but I have no idea what the hell it's doing
that return line is a clusterfuck though
Unless you return it in format_html_join() django automatically turns everything into escaped characters
I wouldn't use that return line if I was writing code for my worst enemy
you can still return it in format_html_join(), just don't do everything on the same line
I mean I can't it just impossible for me
- 83
- 999
- 102
- 34

