#web-development
2 messages · Page 20 of 1
KK. Thanks.
Virtualenv / virtualenvwrapper-win
I can't activate virtual environment :"(
even i run the activate.bat it just crash
and workon just got nothing happen
Okay I'll try at night
I'm in the class now LOL
Oh you using a wrapper thing
You want this command to active your venv: mkvirtualenv workon ENV1
Oh okay I'll try this too!
If I still have problem I'll coming back xD
Is it possible to have multiple forms on one page using flask.
Yes
You would have two different <form> tags with different action values
The actions values would be to where the form will post/get too
I see so if I have resetUser and resetPass forms, resetUser would go to resetUser.html etc?
Yes
Unfortunately, I don't know too much about flask
So I have no clue how to implement that
Just having a quick try
??
Flask does
I've never looked at documentation before
I usally use django for my web stuff
Ah
But flask looks intersting if trying to get something now
from flask import render_template game over
You could build a webapp with this so fast lol
Ok should get it to work got the request data ty
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving
• Keep your patience while we're helping you.
You can find a much more detailed explanation on our website.
@kindred cosmos Finally, I used visual studio......, it will create and activate virtual environment automatically lol
and btw mkvirtualenv workon ENV1 works ! thx u very much >A</
Hey guys, i need a little help with Django.
and postgres database
I'm getting this erro when i try run ./manage.py runserver
django.db.utils.OperationalError: FATAL: Ident authentication failed for user "user"
i already go in psql with sudo su - postgres and created this user
Better way to do this? Suggestions?
def encode_auth_token(self, user_id):
"""
Generates the Auth Token
:return: string
"""
try:
payload = {
'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1, seconds=5),
'iat': datetime.datetime.utcnow(),
'sub': user_id
}
return jwt.encode(
payload,
key,
algorithm='HS256'
)
except Exception as e:
return e
@staticmethod
def decode_auth_token(auth_token):
"""
Decodes the auth token
:param auth_token:
:return: integer|string
"""
try:
payload = jwt.decode(auth_token, key)
is_blacklisted_token = ApiUserTokenBlacklist.check_blacklist(auth_token)
if is_blacklisted_token:
return 'Token blacklisted. Please log in again.'
else:
return payload['sub']
except jwt.ExpiredSignatureError:
return 'Signature expired. Please log in again.'
except jwt.InvalidTokenError:
return 'Invalid token. Please log in again.'
@hollow flower A lot of the methods in the Flask-JWT-Extended, specifically a lot of decorator methods, will handle a lot for you. Flask-JWT-Extended's method create_access_token(identity=identity) will create a JWT the same way you do in your encode_auth_token function, where the identity is the user_id
then you can handle a lot of those exceptions with decorators
@jwt.token_in_blacklist_loader
def token_in_blacklist(decoded_token):
return is_revoked(decoded_token)
@jwt.invalid_token_loader
def invalid_token_callback(error):
return jsonify({
"description": "Signature verification failed.",
"error": str(error)
}), 401
@jwt.revoked_token_loader
def revoked_token_callback():
return jsonify({
"description": "The token has been revoked.",
"error": "token_revoked"
}), 401
(the is_revoked(decoded_token) is my own function which checks if the token in the token database table has been revoked)
I've got my image in Static -> Imgs -> b4.jpg but when I specify background-image: url('/static/imgs/b4.jpg) it doesn't work? I've also tried using flask url_for method but doesn't work. Anyone know what's going on?
I assume you're talking about using that in a template. Your url_for() should look like:
url_for('static', filename='Imgs/b4.jpg')
don't think that's going to work in a CSS file. that's a static file, not processed by the app. I think you'd have to include the relevant CSS in a template file.
1 question, so now i registred my user and i want to send activation tocken to his email but how to make it a link, my only logic would to put API endpoint for activation to be GET so i can constucruct URL , or is there some other solution?
Don't know if this helps but I watched a video that uses tokens for reset passwords you could try the same way but use to validate the email instead ?
what, i need to confirm email exists so i am sending a link to mail so user confirms it
i planed to use jwt but would like to confirm by just sending a post request to my server but issue is how to create a post request as link thats why i think i have to use GET request
@glacial quartz why would a get request not work?
what I do is maintain a database table of activation tokens. I create this token using the token_urlsafe() method of the builtin secrets module. I use 64 as a parameter, which leaves me with an 86 character string. i save these tokens, their creation time, how long i want them to be valid for, and an is_used flag that I set to 0 for an unused token, or 1 for a used token. (can only activate if is_used is 0)
@midnight kernel i wanted to use post, but ye am now using GET cuz cant make a post url
then i have a route that allows for activating the token VIA a get URL
@app.route('/activate/<string:token>', methods=['GET'])
def activate_account_with_token(token):
msg = auth.activate_acct_token(token)
return jsonify(msg)
duno atm i am just on registration creating a mail with token and email in it
and have colum acctivated in user
with their randomly generated token associated with an account
i am using flask-restfull for some unknow reason xD
anyway it works now i just thinked GET is beh wanted to use POST but ye 😃
yeah POSTs are a bit harder to do with a single link
POSTs are more like, when you wanna send JSON data or form data from something
i duno if its even posible to do as link, anyway just now figured out i need to put activated in auth tocken cuz its pointless if i dont have it xD
putting an actual parameter (the token) in a link, I can't think of a reasonable way to do that other than a GET
yep i know thats why in end ended up using GET
@valid tide Selenium
ive looked into it
does the webdriver have any importance?
Hello, I'm having trouble writing my django models. I'm usign the spotify api and i want to save the returns as complete models. reference to spotify here :https://developer.spotify.com/documentation/web-api/reference/object-model/ . For example when i requested a track object it comes with a album object,artist object,external_ids, external_urls object inside. My modals file here: https://paste.ubuntu.com/p/vHGKfFKF4C/?fbclid=IwAR3HzjrDhjSrFI6XgnQmzXZ0AvDmpP6Hca4pJqBpXYPOLArTpg_VzNTPIcc . But this way usign foreign keys or onetofields i cant save a track object without saving external urls first and when 5 related fields in a track object is considered it becomes to much code and too many saves within just a function. Should i reconstruct my modal file any recommendations ?
lmao at dash not having support for native imagery and forcing you to decode and recode stuff in 64 to display a static image
I have django app, where it shows images, and there is categories for different kind of images (Cats, Dogs, Turtles, Elephants ect). What I want to do is, if there isn't any images of that category posted I want it to hide the title (title Cats and under that there is all the cat images).
I hope it makes senses
how much time does it take to learn basic django
As much time as you think you need.
I'm personally taking my time with it, in order to get my feet wet with everything.
have a deadline about 1 week to make something basic so cant take as much time as I would like
If you don't have that much time, then you might want to try to find a recent Youtube tutorial to learn from.
It might be a little difficult starting out, since you're going to be starting out with a lot of modules from the start.
yeah I am going through tutorial atm but I just need to display some database tables or views
if you work hard you can prob run through a tutorial like https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django pretty quick
i learned flask with a similar tutorial in prob just a few hours of total time
tutorials that run you through everything from the folder layout, databases, templating, authentication and some deployment tend to be enough to get rolling
the app they make is usually somewhat simple but it touches everything you really need
keep getting problems with django: ```django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?
not sure what is going on its connected to mysql and making updates
Anyone know, in html if I can make it where my form inputs can only be submitted once every 24 hours?
html?
yes
does html include javascript
I do not have javascript but I have php with the inputs
think you might need to check to see when last input was and see if you want to accept it
well, I just want something that makes it where once you submit, it has a 25 hour cool-down
24*
I didnt know if there was like something in html that you could do that with
Like the required attribute on an input
from what i understand html just displays a webpage
@upbeat forge You can do that by doing if list: print('list has items')
And if the list is empty, nothing happens
Yes
Mm
I don't know how you're handling the images but that's the basic principle
Hello is a way to send array in post via input? <input type="text" name="items[0][value]"> in django?
Hello? Does anybody post here?
from jet.dashboard import dashboard
class Dashboard(dashboard.DefaultIndexDashboard):
class Media(dashboard.DefaultAppIndexDashboard.Media):
js = (
'charts.js',
) + dashboard.DefaultAppIndexDashboard.Media.js
class AppDashboard(dashboard.DefaultAppIndexDashboard):
class Media(dashboard.DefaultAppIndexDashboard.Media):
js = (
'charts.js',
) + dashboard.DefaultAppIndexDashboard.Media.js
Django-jet
chats.js is added to the served template, correct path yet 404
Aye
?
Im new to python and im trying to make some helpful connections while i learn
is there a recommended async framework (for an api)?
i saw sanic security bug, and was wondering what my other options
Did you know. that there's an Fast 3G and Slow 3G options in Chrome DevTools? Are those for testing your website with slow connection and fast connection? Like how fast your website will load?
Because if it's Slow 3G tooks too much time to upload image
Yeah with the highest bottleneck, even the smallest websites fail HARD
Even the most efficient use of resources fail HARD
They think there are still places with 56k modems
#web-development does anyone know a good Discord server for either web design or web development particularly in HTML, CSS, JavaScript?
#web-development my question is in regards to HTML WAI-ARIA role.
I'm designing a informal static website on GitHub and I want to heavily design my HTML side with as much WAI-ARIA as I can but it's difficult for a beginning web developer to exactly how to think about the design concept.
WC3 has good documentation but I need more like a guide to WAI-ARIA and Web accessibility design.
Frankly you shouldnt have to worry much about ARIA tags if you're abeginner, just make sure you have semantically good hierarchy of html, and avoid divs/spans
Now, I'm using flask and HTML, and I'm trying to copy output with a button. my html is: https://hastebin.com/mufoyusisa.xml and the relevent python is:
@app.route("/upload", methods=["GET", "POST"])
def upload_file():
if request.method == "POST":
f = request.files["file"]
fileextention = f.filename.split(".")[1]
filename = str(random.randint(11111, 99999))
filename = f"{filename}.{fileextention}"
f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
results = f"{app.config['SERVER_NAME']}/{filename}"
response = make_response(render_template('upload_file.html', uploadfile=1, response="Done!", uploadedfile=results))
return response
if request.method == "GET":
response = make_response(render_template('upload_file.html', uploadfile=0, response="Drag your file here or click in this area."))
return response
But it'll copy uploadedfile rather than a url
Does anyone know how to make it template properly?
I have a front-end that someone made using HTML/CSS
I need to combine it with a Python backend
How should I go about this?
If you want basic but powerful, flask
If you want a lot of features built in, django
Or if you don't need a backend at all and still want to use python for serving your files for some crazy reason
tornado
I'm currently making a chat bot for twitch and I'm using django to create a web interface for users, I would like them to be able to authenticate via twitch so I have used the allauth module. I have the redirect to twitch working however even after authenticating on twitch and then redirecting back to localhost from twitch, django still sees the user as an anonymous user, there are no errors, just that the url of the page has redirect_mismatch in it. I've tried all combinations of redirect urls in sites and on the twitch developer app and nothing seems to be working.
I had a similar issue to that, and I just created a model that is an extension of the User model. I made sure that one is created automatically for each user on signup. Then when referencing the user I went through the model.
Thanks, I can do that. What about the data about the user from twitch? it looks like twitch is not returning information because of the url mismatch, would I just have to have them enter their details manually?
Pretty basic question, but if my domain is not ssl enabled, when I sign into phpmyadmin are my credentials exposed, or do I connect to phpmyadmin locally?
psure phpmyadmin runs from the server its installed on. so if its not on your local computer everything is exposed
that's what I thought. On to learn about ssl! Thank you @opal leaf !
Look into let's encrypt. It's a really easy way to get your own certificate
@kindred cosmos that is what I am doing currently, thank you. My issue is that I didn't really want to pay for hosting as the site wasn't really meant to be high traffic. This is my first dabble in backend development and using databases, and it doesn't seem there are any free options that give me access to shell.
can people put licenses on css? like they did? https://github.com/IanLunn/Hover
i mean, fade and grow are common css 🤔
@olive wharf Thanks
Hey guys do you have any recommended resources into learning aws api gateway
In particular authentication, but overall
I'm hitting a brick wall with trying to learn it
@split sage of course you can license your code
Interested in nodejs. Is this a self driven language or you have to understand the basics of javascript first ?
How I add CSS to flask website?
I have this but it don't work:
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
looks correct for flask with jinja2
But it don't work
How does it not work? Do you get a wrong url or what?
Any javascript buffs available to answer a question? How can I tie a single function to two different events? I tried making the function outside the event trigger but it always runs the code on launch. I know it's stupid code but my loops weren't working (and compounding things) but that's an issue for another day https://jsfiddle.net/p5hncjgm/ I basically want the script to run when I press the button and when I edit a cell
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
That's windows right? Try Ctrl+F5, that should force the browser to reload all files
all django guides ive seen around dont deal with user input........
basically i want to get data off the user and return an output from an sql database based on their input
ik u gotta use a form and connect it to a url and a view, but i rlly cant seem to get it working
anyone mind helping?
hey i have a question for anyone who knows django
Im creating a commenting feature but theres an error in redirecting
"'Poll' object has no attribute 'get_absolute_url'"
STATUS_CHOICES = (
(0, 'Low'),
(1, 'Normal'),
(2, 'High'),)
id = models.AutoField(primary_key=True, verbose_name=" ")
nmr = models.IntegerField(unique=True, choices=STATUS_CHOICES)```
Any ideas?
Nvm fixed it
mb
Hi people. Any tips for a starting point (ideas) for database/model audit log/trail on Django? Not using third party packages. I'm using. Vue/quasar frontend with DRF backend. I'm after a general approach really. Would you have a single model called audit_log and in there have a single entry which stores user, changed-model(table), etc? But then where to store what field was changed, since this will be different for each changed model type, so can't easily be kept in a single audit log model can it? Anybody got any ideas?
Or would you create a _log model for each model that you want to keep a log for? That sounds more manageable/easy to me, but might turn into lots of repetition in the long term and stuff.
Depends on your use case really. I mean you could make a basic log model, store table row colum pre post. This would also avoid having to alter two models when make changes. When you do make changes to the models and run the migration you can add to the migration script a post to the audit table showing the migrated changes as well. So when you look at it in the future, you can see that hair color colum was deleted but prior to that deletion you can still track previous changes to that model.
@rancid lava
@outer marsh thanks. I'll give that some thought. How about another approach.. what if in every model I have another field that says "superceded_by_id" or something, which basically turns that row into a 'previous record'. Then in my general querysets (where I just want to see current data and not previous data), I just filter to only pull out those where superceded_by_id is null or blank. I'm not sure if this sounds like a terrible idea, or a clever idea. I'm not sure how easy it would be to reconstruct an audit trail from that data then..
it could mess up foreign key links..
hmm
You could do it that way. Just reads the data to the same model referencing the parent pk-id in the new data set, just be mindful these interactions when you transition data to archive tables for lts.
Then mark the parent as not active, and use the parent ID as a foreign keys. The initial record will reference itself.
Eg Select values from table where parent ID = x except from table where active_record=false.
And index active_record, pk_id, and other relavent indexable values.
Honestly there's a dozen ways you can handle this.
If you make an log table and store row column row changes made, update the active record. Then when you need to pull back out the logs you can dynamically do queries for the record you want, since the row, colum, would likely be stored as a str.
I'll have a go! I'm pretty new to all this. I'm using django models and ORM obviously
thanks for your help
Gotcha, np man. Any time good luck!
thanks 😃
row column sounds pretty easy. my only concern there maybe was that if a column was renamed later, then the stored entry, being a string would be the old name, but.. maybe that's not such a big deal
Since you will still reference each record independently based on pk,
Since you will still reference each record independently based on pk,
To be clear when I say row I do mean individual records. So you'd store the row/pk, str(key/column), str(previous value)
yes that's how I understood it too.. seems pretty easy that. I'm just reading up on existing packages to see if they do stuff that I hadn't thought about though 😃 e.g. django-reversion and django-simple-history
Yup. You can use packages and save time.
But sometimes it's useful to build a thing so you learn how.
I guess it would look like: changed_row_id, field_name, old_val, new_val, user_id. Unless I was to try to be clever and just reconstruct the order/history (i.e. work out 'new' val each time). I can imagine trying to build up a list where a field has been changed a few times though
oh and datetime stamps of course
and model_name
(This question might be more appropriate in #databases, but this is not strictly a database-question, should we need a "software engineering" channel?)
I am asking myself a question about data model in a web app when it comes to "large" models. Would you consider it a bad practice to split large models into multiple smaller ones using one-to-one relations, e.g., in Django:
from django.db import models
class Foo(models.Model):
x = models.Field()
y = models.Field()
ax = models.Field()
ay = models.Field()
bx = models.Field()
by = models.Field()
Would become:
from django.db import models
class Foo(models.Model):
x = models.Field()
y = models.Field()
class A(models.Model):
foo = models.OneToOneField(Foo, on_delete=models.CASCADE)
x = models.Field()
y = models.Field()
class B(models.Model):
foo = models.OneToOneField(Foo, on_delete=models.CASCADE)
x = models.Field()
y = models.Field()
This sounds okay to me in accordance with single responsibility principle, since these "submodels" would obviously encapsulate behavior specific to them.
I have however read several times that "one-to-one relations should be kept for inheritance or third-party model extension", without much more explanations.
What do you guys think? 🤔
Question: do ppl acc use python for web dev
Don’t ppl just html more
@weak temple yes they use djano, flask, etc. Django is awesome. I am using django with rest-framework as a backend for a Vue.js2 front-end. it's spiffing.
@unborn terrace I don't know. I know the django docs say what you've said - that one-to-one fields shouldn't be used where it would make sense to just extend the original model, but I am using one-to-one in exactly the way you've said. i have done it because one of my models is imported from another system though, and I wanted to keep the model replicating the source api feed exactly, and then extend it with other models linked via OneToOne fields
Hey guys I have some news
good news and bad news
good news I've applied to Sky for a software engineering apprenticeship
and i've gotten to the next stage after submitting my applications
bad news is i have an unattended test... and i have to make a webpage with interactive buttons etc which i have NO experience in /:
What I'm looking for hopefully is if someone could help me at least where to start or some sort of guidelines i'd appreciate that hugely... they only gave me 3 days to do it.
here's the task brief... thanks in advance to anyone who might help
Hi, I'm using Flask for creating a website. I know it's possible to create role based authorization (or use flask-login for it) but I was wondering if it's possible to create role based routing (and how)?
For example
@authenticated.route('/Home
@login_required('admin')
def sa_homepage()
#returns homepage for superadmin
@authenticated.route('/Home
@login_required('guest')
def guest_homepage()
#returns homepage for guest
The same endpoint, but different function based on the role. OR am I just over complicating this and it would just be fine to have 1 function with a simple if-check to see what role the user is? Thanks
@violet zodiac u from the uk?
yep
@violet zodiac I think you should be looking at a client side javascript framework for that. Vue.js. You could look at quasar framework which will make using vue even easier. look at https://v1.quasar-framework.org/start/pick-quasar-flavour and at the Vue Components bit. 3 days is not long enough to learn from scratch though. It wasn't for me anyway, but i'm 37 and learn slowly now I suppose 😉
or, I suppose since you only have 3 days, knock it up in jQuery
I mean my last hope right now is probably relying on internet resources and templates
I'll probably have to find a project online and tweak it...
I mean I know how to use QTdesigner but I dont think it's possible to make a webpage with QT
im not sure people use python for the frontend stuff
I assume most of it is done in javascript or css
Hey guys, anyone can help me clarify what's this error means?
TypeError: NetworkError when attempting to fetch resource.[Learn More]
I'm using Python with Django + Rest in back end
and React.js in front
The API is running OK, with no problem.
But nothing renders in the screen
I have see another problem too
The API doesn't have nothing inside it.
it's empty, whata hell.
Hi anyone here is familiar with TCP servers?
@native tide doesn't have nothing ?
you can do better than that 😉
@native tide you can use cors middleware to try to allow the cross origin request, but better option is to proxy from frontend to back end.
that's what I am doing with Vue & django-rest-framework. My webpack config proxies to the backend. So everything is on the same origin as far as the browser is concerned.
@native tide e.g. inside my webpack config: devServer: { host: 'my-hostname.whatever', // https: true, // port: 8080, open: true, // opens browser window automatically proxy: { '/api' : { target: 'http://localhost:8000', secure: false }, '/static' : { target :'http://localhost:8000', secure: false }, '/admin' : { target: 'http://localhost:8000', secure: false }, '/__debug' : { target: 'http://localhost:8000', secure: false }, '/auth' : { target: 'http://localhost:8000', secure: false }, '/accounts' : { target: 'http://localhost:8000', secure: false } }, },
might also need to put an entry in your /etc/hosts or %windir%\system32\drivers\etc\hosts with my-hostname.whatever pointing to 127.0.0.1
maybe
@native tide essentially your issue is that back end and front end, whilst being on the same host (localhost) they are on different ports (:8000 and :5000), which is why you must proxy and just access all on the front-end port.
hey there. does anyone know the proper way to concatenate this?
entry_1 = request.POST.get(f"item_{x}")
Hey, someone would already be working with Flask-SocketIO or can inform me generally about the scaling of a Flask server?
How much time would it take to get Django up and running on a server?
That depends on what you mean by that
I have basic Django tutorial done need to put it on a server
Do you need to write the whole server or are you just talking about deployment?
Yeah just deploying it
Doesnt have anything fancy just want to get it onto a server
Okay, what kind of web server did you have in mind?
Debian probably Apache MySQL
If you know what you're doing, deployment can be fast
It's fairly easy, the documentation has some info on it here: https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
Obviously, more advanced setups require more planning
So, it depends a bit on how complicated your production environment is
Just deploying the basic tutorial for "home" use should be fairly straightforward
Setting up a production environment for a large organization is something else entirely
Oh thanks that looks doable
Hey guys. I'm just starting to get into front-end development after learning backend development for a bit. What are some recommend programs/modules/etc. to make a really really clean and nice. I looked at things like TKinter etc for this but they have really really ugly frontends imo, so was wondering on what other options are there.
Define public data?
https://website.tld/robots.txt
hello. i'm looking to get some help on a regex. is this the right channel?
What do you need?
can i ask a beginner html question?
Don't ask to ask, just ask. =]
How do you concatenate strings in variables {{ }}?
i tried {{ str1.concat(str2) }} but it didn't work.
and i tried {{ str1 + ' ' + str2 }}. this didn't work as well...
It isn't html. It's some kind of templating language.
What do you use besides html?
i use django templates
i tought this was html because i use vars ({{}}) and tags ({% %}) in my templates.
Well in that case what stops you from just doing {{str1}}{{str2}}?
ah, i tought it would just make a new line and insert str 2 there.
its my bad not trying tough
brb
No worries. =]
it did it thanks
👍
"str"|add:"str2"```
I'm a django dev, sorry to disappoint
yo anyone know how to change the colour, size and font of this?[typed string0="I'm Alfie Skinner" string1="" typeSpeed="40" startDelay="0" backSpeed="40" backDelay="500"]
@pearl grove if you let me know what database you're using, a code sample, and any error messages, I might be able to help.
Hello all. I am looking for some insight. I have been coding with python for a few year self taught. Just to automate some jobs at work, working a lot with requests, and then transforming the data and doing things with it. Wether it be a Telegram bot or iterating over csv files etc. I wanted to start working with some web application stuff with python since its the language im the most comfortable with. And I am going thru a little tutorial and in the example the database used in sql. In all of my past examples with retrieving data its always in a json response. Any little project I've already created stores everything in that structure. Is it possible to use sql and still query response in json?
You'd only need to use one. If you're unfamiliar with sql or don't want to use it, you could store your data with json.
I'm ok with sql i know how to query I just can't understand it in from a web development point
especially when dealing with arrays
What database would I be storing json to?
If you're using sql there's no need to use json, is my point.
What kind of data are you interested in storing?
I'm plan on developing a game
so I would be storing data per game
The idea is to create and start the game from the web interface. I will then scrape a separate API at an interval for changes being made within the game being played updating all values in the database. Which would then update the web UI without a refresh (very important)
I have a text based version of this working but it is not asynchronous so multiple games can't be ran at once. And all data is stored in memory
Right, reactive frontend and perhaps even a socket connection to speed up communication.
teams = {'Team1': { name: 'Team Name', "players": [{name:Player, stats:{kills:0, deaths:0, wins: 0}] },{'Team2': { name: 'Team Name', "players": [{name:Player, stats:{kills:0, deaths:0, wins: 0}] }
Something similar to this is how I am storing it in memory now
Is each team an active session or the teams in one session?
When you talk about json, do you mean that you store this dictionary in a file, or just that you keep the data in a dictionary?
keep the data in a dict
never store it - script runs and actually use google sheets api to write data to a sheet and update the sheet as time goes on
end users can view the sheet for the score changes of the game
Sure.
rather than use this hacky way. I was going to try and implement in a web applicatioln
Then your server will keep the data for the active sessions locally, and will have to upload it whenever it sees fit.
What part of the client-server API do you have?
What do you mean by that?
What code do you have so far?
I have the full code written for the example I stated above. Nothing using Django + React
was going to start following some tutorials and when I did it was recommending sql as the server for django and if your not going to use some form of sql then your not really leveraging the benefits of django
Right, Django has an entire SQL querying toolkit that you'll be using. You'll set up your data using models.
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
There's a lot to explain here, so I'd suggest looking up a Django tutorial. They cover models and databases which allows you to store your Games, Users, Sessions and all kinds of stuff.
the websocket thing looks really interesting
It's very useful and allows for direct communication between the client and the server.
Normally, the server isn't able to ping the user when something updates, but with sockets the server can announce players actions to everyone.
Last time I worked with Django and reactive web design, I was making an online board games site. For active games, I used a Redis database which keeps session specific data as long as it's in use, although it took a while to set up.
Not sure if its a problem but I am scraping a separate API from the PC game I am building this for. So not sure how I'd build events off that
All seems a bit above my head so I better start small
Getting started with a basic Django website is a good start, getting used to setting up an API.
thanks for the help @still briar
hi
how do i automatically update a django page without refreshing the page manually
👍
You want the client to change to a different page without refreshing? That will require some frontend coding.
no basically i want it to be connected to a web socket. When the websocket is not on it shows the next shows time and prize. when the show is on it shows different variables like questions, players remaining etc. When the websocket is active or some variables change how do i update the page with out refreshing it.
You'll need to get familiar with reactive programming for your front-end.
Essentially, updating the client html without refreshing. The client communicates with the server via http requests or websockets, and upon receiving data, you'll have to insert it however you please.
There are various frameworks for easy reactive programming, such as React or Vue, but you can do it with some basic javascript or jquery yourself.
would django channels do the job?
No, that's just a protocol on the server. You still need javascript on the client to load things as they come.
How does your frontend client code look at the moment?
Yes, but your frontend, the webpage, needs to call an url that links to the server.
If you've only made a static page, the client will only visit the url once and nothing will update.
But by using javascript, you could manually call something like website.com/get_all_players and receive a list of players from the server.
Done this kind of thing before?
nope
Are you familiar with javascript?
not really
This is going to be rather tricky in that case.
would it be something like this: https://guwii.com/bytes/easy-way-of-automatically-updating-web-page/
Yes exactly!
ok
Normally what happens is that when you load a webpage, the client sends a http request to the server, and the server returns html that is loaded into the browser.
When you want to update the website without refreshing, you'll need to make that http request yourself, which allows you to do whatever you want with the data that comes back.
wait so this is the code
<script type="text/javascript">
function refresh() {
var req = new XMLHttpRequest();
console.log("Grabbing Value");
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
document.getElementById('guwiiFavouriteNumber').innerText = req.responseText;
}
}
req.open("GET", 'reload.txt', true);
req.send(null);
}
function init() {
refresh()
var int = self.setInterval(function () {
refresh()
}, 10000);
}
</script>
would i have to change the req.open to the variable I want to refresh
req.open("GET", "/get_something", true)
This will make req call that function in your views.py
in my code i acess it by saying {{NextShowTime}}
The req.onreadystatechange function is called when the server returns something. To start off, you could change the document.getElementById... thing to console.log(req.responseText);
That's a template variable in the html.
What does your views.py look like?
from django.shortcuts import render
from . import networking
def home(request):
context = {
'NextShowTime': networking.NextShowTime,
'NextShowPrize': networking.NextShowPrize,
}
return render(request, 'hqsite/beforegame.html', context)
Ok, let's add another function here!
ok
You should have a urls.py as well, right?
yeah i do
Let's see that one.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('hqsite.urls'))
]
Not entirely sure what hqsite.urls is supposed to be, but somehow it calls home?
yeah
Then where is home specified?
from django.urls import path
from . import views
#from users import views as user_views
urlpatterns = [
path('', views.home, name='hq-home'),
#path('register/', user_views.register, name="register")
]
Yes ok, that makes more sense. This is the one you need.
Here, you can add a new path to a new server call you wish to add. Let's add a greeting.
path('say_hello/', views.say_hello, name="say_hello"),```
ok
k
def say_hello(request):
return HttpResponse("Hello world")
Now, the goal is to have the client use a XMLHttpRequest to call say_hello/
ok
Is using Electron a viable option to making a GUI for a Python program?
@tardy roost Hey thanks!
I'm using firebase' firestore database, a flask server.
I want to POST request with a image, compute another script on that image, label it as "pass" or "fail" and return
actually I'm new at this
can the request GET and POST at the same time like
localhost:5000/upload/<uid>
and get a result like
"uid": {
"img_url": "firestore url ref",
"img_label": "fail"
at backend I'm running a script which predict something
is it doable?
please tell me if I'm doing anything wrong
which I'm pretty sure about
thanks for you time
Is your current code working, or what happens?
it's working now
but not how I wanted it to be
did you get it?
also firebase_admin in not implemented yet
Anyone know any good websites for getting text,images and other stuff on a web page to float into view. (Like the powerpoint animation) So that when someone lands on my page all the images and text sort of in sync load
Im trying to make a marketplace alike website, but I need a payment proccesor that allows me to set a commision rate
so that whemever someone buys something a percentage goes to me
anyone knows a payment proccesor that allows this? I cant find one
hm i always assumed that the sites that did that took the money from the customer themselves then later paid out to the seller
apperantly stripe allows to set a commision but there fees are high + they dont accpet pp
and btc
yeah it is DEF more complex
you have to have an account to hold the money paid by the customer, then you need a system that is VERY reliable to keep track of the sellers and what the current status is of each payment
AND you have to handle refunds somehow
ye I would probs have to manually review payout requets
there are prob legal things you have to deal with too when holding money like this
looks like woocommerce supports commissions https://ecommerce-platforms.com/ecommerce-selling-advice/how-to-build-a-physical-product-marketplace-like-etsy-with-wordpress-and-woocommerce
not sure exactly how it works but this tutorial shows them selecting a commission amount
I was just reading somethinbg bout it
but is it a payment proccesor
or a marketplace maker
looks like the name of what you want to make is "multi vendor marketplace"
yeah not sure yet lol.
Built-in payment processing from leading providers: Take payments via Stripe and PayPal. Accept credit cards, Direct Bank Transfer, checks or Cash on Delivery.
looks like its software for the site that can interface to payment processors
What about storage? We do not host or store any of your files or information. This is dependent on your hosting solution.
its just software that can do this stuff it looks like
and it interfaces to wordpress, so yeah you can customize it
hmm I'll have a look at it
there are other products like this it looks like, i think "multi vendor marketplace" is the magic phrase that will find it all
def queryset(self, request, queryset):
value = self.value()
return queryset.annotate(
age=int((datetime.today().date() - F('birthday')).days / 365.25)
).filter(age=value)
Django doesn't seem to like this annotation
'CombinedExpression' object has no attribute 'days'
looks like you did int(stuff).days
I didn't tho
Would error differently
def queryset(self, request, queryset):
value = self.value()
return queryset.annotate(
age=int(
(
datetime.today().date() - F('birthday')
).days / 365.25
)
).filter(age=value)```
oh woops i misread. so doing some reading it looks like you need to tell it what type to output:
https://docs.djangoproject.com/en/1.9/ref/models/expressions/#using-f-with-annotations
or use only django time functions to get now
If I wanted to create a function that would run on a loop for 60 minutes. Is it best to use celery?
For example when a user presses a button, it triggers a function to run as a celery task and within that function is a while loop that would run for 60 minutes.
I want to create a "game session" that lasts for 60 minutes
Function run on a loop for 60 mins
vs
Function loops every 60 minutes
Second one is celery
First one is depends on the specific situation
it would be the first option
The idea is that the end user can create a game "session" on the front end. Once they create that session. I want to query an api every minute for 60 minutes, updating my database to pull into a view.
So press button - run function, for 60 minutes that loops every minute updating database with an option to stop the loop
i thought I would use celery tasks to run that function that way the entire application isn't waiting for the 60 minute loop to finish
Hi all
I have an odd situation here.
I have a table here that Django is rendering as HTML. And it actually does it correctly. But it results in plain text rather than HTML code.
Here's what I have:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ schedule }}
</body>
</html>
#resulting html in browser
<!DOCTYPE html>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th></th>
<th>Mon</th>
<th>Hosted by</th>
<th>Tue</th>
<th>Hosted by</th>
<th>Wed</th>
<th>Hosted by</th>
<th>Thu</th>
<th>Hosted by</th>
<th>Fri</th>
<th>Hosted by</th>
<th>Sat</th>
<th>Hosted by</th>
...
The function generating the table is this:
def schedule():
s = Spread('name', 'table')
s.open_sheet(0)
df = s.sheet_to_df(index=2)
pandas_df = pd.DataFrame(df)
return pandas_df.to_html()
I suppose it's because pandas function .to_html doesn't properly render the dataframe?
Figured it out. Had to use {{ schedule | safe }} in the template
I want to edit django user's groups and change crud permissions but
Django doesn't automatically create the CRUD perms for my model
Even tho docs claim it does
Anyone know of a good Django rq tutorial
RQ?
rq redis
can anyone help me to try and make my current website mobile friendly? Its a pretty short page
@orchid aspen Try:
<meta name="viewport" content="width=device-width ">
hi am using flask and i have 1 question, whats best way to validate recived input?
i saw that page that uses sqlachemy model for validation but that whay i have to try write to db first to give error and my logic is i should validate inputs before they even reach db, second i used regparse form flask-restuf but its writen there that its outdated and should not use it
basicly i am making an api and am just dealing with jsons
need to check if recived json valid contains all feelds i need and if they in right format
@glacial quartz webargs and/or marshmallow
Anyone around to discuss django background processes?
@native tide where would I add this
hmm am trying to mix flask-restfull with webargs but it shoots me errors
is flask-restfull too old should i use flask-restplust or what?
what are the errors?
@inland veldt i frogot to add args in def post
def post(self, >>args<<):
is there any point of using abort(400, "some error or soemthing")
isted just returning json msg:"some error or soemthing"
does 400 code give me anything?
how would I stop flask sending out these annoying messages
By not using flasks debug server.
it still does it
I mean the dev server.
how would I do that? I was just doing app.run
use wsgi or any other server
You'll have to use something like apache or nginx that can work with wsgi
ok thx
Hello, I have a an issue in Django with generic foreign keys, I have these models:
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation
)
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Foo(models.Model):
sub_content_type = models.ForeignKey(
ContentType, on_delete=models.PROTECT, null=True
)
sub_id = models.PositiveIntegerField(null=True)
sub = GenericForeignKey('sub_content_type', 'sub_id')
class Sub(models.Model):
foo = GenericRelation(
Foo,
content_type_field='sub_content_type',
object_id_field='sub_id',
related_query_name='sub'
)
class Meta:
abstract = True
class Bar(Sub):
...
Obviously ran makemigrations, added contenttypes to apps and stuff.
The issue when I am trying to create a Foo, like this:
bar = Bar.objects.create() # ok
foo = Foo.objects.create(sub=bar) # error
The last line raises the following error:
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use sub.set() instead.
After triple-checking docs and SO, I still can't find the issue, do you see something wrong here?
quick questiong regarding quart_openapi
manager = PintBlueprint("manager", __name__)
@manager.route("/")
class Manger(Resource):
async def get(self):
return "Get"
async def post(self):
return await request.get_json()
how can i access the request when using blueprints
I have a really long web development question, just private dm me please
@lucid girder you can ask it here
@orchid aspen sorry for the delayed answer. (I dont usually get on until night) You would add that in the head.
@woeful vapor
"Loops over itself every minute for 60 minute" not gonna work in Django without a task queue http://docs.celeryproject.org/en/latest/getting-started/introduction.html
WSGI appllications aren't meant to have threads that run this long
oh
wait, I think I misread. The function calls Django? So it's something outside of Django?
i want the b to be on the same line as all the other links but still be aligned right
How are you currently doing it?
text-align: right;```
Using just that would make everything to the right.
yep wait let me get a better example
<header>
<a href="#" class="title">bb</a>
<nav>
<a href="#">a</a>
<a href="#">a</a>
<a href="#">a</a>
<a href="#">a</a>
<a href="#" class="right">right</a>
</nav>
</header>
.title {
display: inline;
}
nav {
display: inline;
}
iirc you would need to make them float.
but is it possible without float
wow wait
when i used float before it broke when i used padding in the header but for some reason it works now
i am confused
my float always broke with padding but now it works, i used to hate float because it broke with padding
html/css can be quite complicated.
yeah
and when i set the font-size for the title the .right will float right and up to the top
i want it aligned with the other links (a)
.title {
font-size: 1.8em;
display: inline;
}
nav {
display: inline;
}
.right {
float: right;
}
||nederland is kut en nat altijd 😹 ||
@quiet solstice
I managed to get them on the same line. It's the top line though 😅
how?? and is there a better way of doing this??
Maybe someone else will know how to do this.
@prime ridge isn't that what Django background tasks is?
Hey there!
I wrote a small flask API and I want to run it on my Digital Ocean VPS, I have nginx running on port 80 too which is for my php image uploader (which I didn't code but it works).
So my goal is to run flask script on port 5555 along with nginx and bind it to one of my domains, I tried following one of Digital Ocean tutorials but it didn't work. I checked did I do the steps right and even asked my friend to help but we couldn't find the solution to it. I'm on Ubuntu 18.04 and this is the support link I used:
https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uswgi-and-nginx-on-ubuntu-18-04
Ping me if you respond.
@errant fiber what doesn't work? what's in the logs?
It says that .system file failed and that its because it couldn't bind to port 5555 and it says the another reason is "exit-code"
if it can't bind to a port its usually because another process already has it
so you're running flask on 5555? what's the exact error message?
I heard that it should have permissions to bind under 1024 or something
And I tried with root didn't work
@rough jasper transform = transform(10%); play around with this and apply it directly to the text
You may have to make the button as a whole position: absolute;
@errant fiber are you following https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uswgi-and-nginx-on-ubuntu-18-04?
Yes
No, how do I do that?
last week I tried to use this tutorial on my raspberry pi, I dropped after 2 hours and just used gunicorn
What's the best way to throw together a simple bootstrap site? I know the basic structure of bootstrap sites but I'm kinda interested in some tools that'd help me pull together something generic really fast..
they're for flask apps, so
flask-specific advice is welcome too
(I'm good on the backend code. Frontend just messes me up.)
I feel like a dork asking for advice on this -- I'm mostly a backend dev, I know I should be decent with HTML/CSS/JS but I just don't have to make user-facing content often enough to be good at it
You do it yourself.
Never seen a back-end only python web-dev
@sharp briar boooo. I know that's the obvious "best for me" answer but I'm serious -- I will learn my way around the tools well enough to make something from scratch eventually but there are definitely options out there that make it easier for beginners to slap a frontend on something.
Just looking to see if anyone had any recommendations for ones better than what I've managed to find. ide plugins, stuff like code pin, anything to give me a little bit more substance than copy and pasting from the bootstrap docs
wix
Like, I basically write a lot of simple tools that just need a web form and to tabulate data
but when I try to write interfaces like this... They come out okayyy, but not really. And it'd take me a few hours
as opposed to a few minutes.
I did look at webflow though
Seemed like it was a little more involved than I'm looking for.
I guess what I'm after is for something to help me prototype/get a first draft of a site for me to expand on. I'm comfortable changing something about a site when I have a good foundation -- but when I build the foundation from scratch it always turns out subpar =/
You can use a decent ui framework like Bulma or something. Just copy/paste the html for each component
Not unlike bootstrap although bootstrap is just not great
Hmmm. I'd probably have to talk my team into considering a different frontend
Oh so it’s a team and they want to use bootstrap
my boss doesn't actually care but one of my coworkers got pissy when I used materialize for something
Hopefully they don’t plan on doing a react front end or anything
Hahahah. They tried.
Bootstrap is bad if you want to use other js like that
Then is there budget for a tool that does what you want?
I know some decent ones that cost something monthly
Fewer or none now that are free
I just buy my own tools usually. I could get them to pay for it but I'd honestly rather not ask...
here is bar none the nicest tool of this sort i have ever used: https://pinegrow.com/
A professional visual editor for CSS Grid, Bootstrap 4 and 3, Foundation, responsive design, HTML, and CSS. Convert HTML to WordPress themes.
I've seen this around. One of the only big ones I haven't tried yet
I really like https://pingendo.com/ it's just a little light on features. Hoping to find something like that but better.
i think its an unlimited trial
Gonna try Pinegrow.
yeah pingendo used to be totally free
and shittier than pinegrow so i tried it anyway since free
no longer free
maybe is nicer now
i dont use any of these web frameworks but i was still very impresseed by pinegrow
I tried webflow but it seems engineered toward designers instead of someone looking for something quick-and-dirty.
Would take me longer to build something in webflow than to write the HTML/CSS by hand so what's the point... Good for someone, just not for me. Installing Pineflow now
pinegrow
lol
well it might be more for designers
oh btw I work at a school so I get a lot of discounts on software :D
but engineers dont usuallly use gui prototype either
youre seeking something for a rarer use case
Yeah, I know they don't... It's not like I'm unwilling to learn. I've written everything by hand up to this point
it's just, I'm kind of a fetishist for doing things really quickly
web design is so slow and tedious and most of the tools I write don't have to look good, it'd just be nice if they did.
learn a bit of css, and then use tailwindcss 😃
fastest layout/design tool on earth once you get the class names down
ooh
So you mostly add classes to objects to stylize them instead of writing CSS... But it's different than bootstrap because the classes are actually visually descriptive, rather than just being generic things like "info" which is blue by default or something for some reason
I like.
Pinegrow looks very promising, thanks for showing this to me.
no problem
and yes to your analysis of tailwind
its not batteries included liike bootstrap but once you memorize the class shortcuts you can make anything in minutes basically
as long as you know what you want it to llook like haha
I imagine I'll pick up more overtime as I work with the output of these programs... Also hmm
but until thats your job maybe give this trial a go
I'm not sure I ever do know what I want things to look like. I imagine we'd probably want to figure out what classes we'd want to use to fit our aesthetic which is... yeah, definitely not my job and hopefully never will be!
yeah plus youd have to get eveyrone to do this
its quickly picking up speed in the dev community but its not for everyone
its for those who dont use things like bootstrap but still need a very fasst and efficient way to build it and see it instantly and not have separate prototype/final phases
ahh
anyways. pinegrow may be good for now
Yeee. Should do me for these small projects I try to turn around in a day
haha a day
I'm insane!
Just... not on the frontend
(I mostly make, like, data pipeline tools. Talk to this database and this API and this user... blah blah blah)
sure
Does anyone here have experience in flask?
I've made my first small python-app-in-site-form using some really basic flask stuff
but I'm getting odd behaviors that I don't get when I run it locally
it's as if it's continuing to store my variables, even after the function 'returns' the html to display
(or at least that's my best guess at what's happening)
What's your code like?
It could be due to how browsers cache the information so you might have to force restart it
well, it's happening where when someone else on another computer runs the site, they are getting some of the variables from when I had input data
my code is a bit long, I don't mind posting it if necessary
but basically the site is taking form input, processing that and building an object of a class
and then attributes from that object are being distributed out through a string
it's like a madlib, if you're familiar with those
Maybe you could use some sort of pastebin to send the cod
ok, give me a min
the flask portion of the code: https://pastebin.com/YWYFH9KM
the class "header" (not sure the term with python): https://pastebin.com/P7Dj0sWv
also with that header file, it's got a couple very long dictionaries, sorry about that, but obviously they can be ignored
actual processing starts around line 262 in that one
ok well, I still don't know why it should be storing those variables, but it was because of my use of the append method for the list it generates
when I switch it to insert, all was fixed
Could someone help me with blueprints in flask? I'm quite new to Python web frameworks and I don't quite understand why it doesn't work. I've looked almost everywhere including docs and stackoverflow, but I am missing something.
@limber orchid unrelated to your question, but you should really consider using templates for your HTML, especially since you're already using flask.
what are you using to run the site when its not local?
yeah I just wanted to get up and running without having to learn the whole library.
but point taken, for sure
I'm using pythonanywhere
and what's the exact behavior? User1 POSTs to the form, the correct information is returnd. User2 POSTs to the form, and User1's data is returned?
basically
the input calculates some planet placements (it's an astrology madlib toy) and then creates a list of strings based on the placements
that list gets returned and the html gets generated with elements from the list placed into that string
so, I think it's still taking the input, but because I was using list.append(string) and my output was using constants for the list index, user1's list was being used to populate
switching to list.insert(index, string) fixed it
but it feels like a bandaid
I have a Flask page @app.route(/videofeed), which runs a program. It only turns on whenever I access the /videofeed page. The problem is when I close that page, the program still runs in the background. Is it possible for Flask/Nginx/uWSGI to determine that the page was closed and it can now terminate the program?
newbie question: i would consider myself a beginner web dev (mostly back-end experience and meh at front-end). where can i find good practices for front-end development? i would really like to improve my HTML/CSS game
Try to copy a website design and see if u got it right @wanton spruce
class TodoForm(forms.ModelForm):
class Meta:
model = Todo
fields = ['title']
how can i add a placeholder to title??
class TodoForm(forms.ModelForm):
title = forms.CharField(max_length=25, label='Title', required=True,
widget=forms.TextInput(attrs={'placeholder': 'PlaceHolderHere'}))
class Meta:
model = Todo
fields = ['title']
Haven't tried it but something like that should work
@rough jasper
Thnx
Hey guys, I'm really struggling to get my flask app deployed to Heroku, I keep getting a cannot parse Procfile error. I've installed gunicorn, my app is in darwinapp.py and in that it's just app = Flask(__name__) so the procfile is just a file (no extension) named Procfile, with a capital P, at the root of my project, with the contents web: gunicorn darwinapp:app
Where am I going wrong with this?
I'm using a Windows machine, do I have to use Procfile.windows?
Traceback (most recent call last):
File "C:\Python\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Python\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "C:\Python\lib\site-packages\django\core\management\base.py", line 379, in check
include_deployment_checks=include_deployment_checks,
File "C:\Python\lib\site-packages\django\core\management\base.py", line 366, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Python\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Python\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "C:\Python\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "C:\Python\lib\site-packages\django\utils\functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Python\lib\site-packages\django\urls\resolvers.py", line 533, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Python\lib\site-packages\django\utils\functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Python\lib\site-packages\django\urls\resolvers.py", line 526, in urlconf_module```
File "C:\Python\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Nils\django_test\mytestsite\locallibrary\locallibrary\urls.py", line 34, in <module>
path('', views.index, name='index'),
NameError: name 'views' is not defined```
^ Can someone help me with the above error
😄
It pops up when i try to run my server in powershell
@stray prism gunicorn does not work on windows whatsoever
Hey guys, I'm running into issues deploying my flask app to heroku I'm currently getting a 404 error but my App is no longer crashing
is it the same syntax as slack to do the thing like up there^
2019-03-07T19:43:24.659586+00:00 heroku[router]: at=info method=GET path="/" host=scratch-and-map.herokuapp.com request_id=ff134f5d-11a8-4fdd-92e5-28bc00a6e2b3 fwd="71.139.123.197" dyno=web.1 connect=0ms service=7ms status=404 bytes=380 protocol=https
2019-03-07T19:43:24.659284+00:00 app[web.1]: 10.61.206.144 - - [07/Mar/2019 19:43:24] "GET / HTTP/1.1" 404 -
guess so lol
well that looks like flask is causing the error
or gunicorn if youre using that or whatever youre serving it with
(i just pinged it as well a couple times)
@tacit orbit are you positive the route works locally? just '/' with no path or anything
how are you running the flask app in your Procfile if not gunicorn
@junior cloak I actually managed to get the app running by redoing my Procfile earlier!
web: python server.py
@stray prism really? gunicorn has long claimed to have no windows support
Looks like we managed to break it. Might be the 0.0.0.0 route
@tacit orbit you need to make sure its on 0.0.0.0 and binding to the port heroku gives it in the $PORT envvar
also you should use gunicorn and not flask.run
unless youre just playing around but if 2 people hit the app at once it's going to freak out
PORT = int(os.environ.get("PORT",5000))
DEBUG = "NO_DEBUG" not in os.environ
app.run(host="0.0.0.0", port=PORT, debug=DEBUG)
mmm okay I'll try setting up gunicorn
does '/' load locally for you for sure
no it doesn't
Can you guys help with a flexbox issue i'm having?
what does the @app.route look like
Or should I come back later?
I can hit you with that flexbox stuff!
@app.route('/')
def index():
return '<h1>Landing page</h1>'
* Restarting with stat
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask_marshmallow/__init__.py:32: UserWarning: Flask-SQLAlchemy integration requires marshmallow-sqlalchemy to be installed.
'Flask-SQLAlchemy integration requires '
could this be it?
Ok so...
I want my flex-wrap to respond to more than just the website edge.
I want it to start flexing if its going to hit another item on my page...
@junior cloak Yeah it shows up on heroku when I go the address
That looks like it's wrapped
Should probably use a mediaquery then
;/
how do you have your css set?
.options {
font: 400 4.5vh/1.2 "Century Gothic";
display: flex;
flex-wrap: wrap;
color: white;
padding: 4vh;
float: right;
text-align: center;
background-size: cover;
background-image: url("images/holder.svg");
}
I want to use float because it allows the elements to not overlap
If i set top:0
Yeah I don't see flex-wrap working for that.
Ok.
you don't want it to like
It works when top: 0 is set
X X X
X X
X
X
X
X
do you?
.options {
font: 400 4.5vh/1.2 "Century Gothic";
display: flex;
flex-wrap: wrap;
color: white;
padding: 4vh;
margin-left: 60vw;
margin-top: 0;
text-align: center;
background-size: cover;
background-image: url("images/holder.svg");
}
Yeah that's fine
This is still acceptable
@tacit orbit i'd think your error was somewhere else since thats just a warning but may as well try. without seeing all the code i don tknow where the 404 would come from
margin-left: 60vw;
@tacit orbit
<div class="options">
<a class="optionp" href="./about/index.html">About</a>
<a class="optionp" href="https://facebook.ewanskinnerltd.co.uk">Photos</a>
<a class="optionp" href="https://facebook.ewanskinnerltd.co.uk">Social</a>
</div>
That's just a margin though, isn't it? and not the width?
If you set the width to a percentage width then you might actually be able to get flex-wrap to work especially if you set the anchors right there with some padding
Padding does effect it?
It should, yeah
But not margin?
Margin might
but also I'm talking about setting padding for each of the anchors and not for the options container
your app.run() is before all the routes
haha
Look dude
I'm new to this python stuff
thanks I'll make that change hopefully it helps!
I was treating it like server.listen
sorry i didnt mean for that to sound insulting it was not
where you have at the very bottom the app.run()
thats where it belongs
you also have it up top though before all the routes
have it in one place at the bottom
Can I just replace it? paste it over that one?
sweet
just replace the app.run(debug=True) with app.run(host="0.0.0.0", port=PORT, debug=DEBUG)
My issue now is that the API token that I've got doesn't seem to be working when I try to access my test page. I've put it into a config var called DARWIN_KEY but it keeps throwing a 500 error code.
Here's my relevant code:
app = Flask(__name__)
DARWIN_KEY = str(os.getenv('SECRET_KEY'))
...
response = requests.get("https://huxley.apphb.com/all/" + str(departure_station) + "/to/" + str(arrival_station) + "/" + str(user_time), params={"accessToken": DARWIN_KEY})
But when I try to access the page I get the following in the traceback:
2019-03-07T20:10:34.195763+00:00 app[web.1]: requests.exceptions.HTTPError: 500 Server Error: Internal Server Error for url: https://huxley.apphb.com/all/tth/to/ecr/['0821',%20'0853',%20'2147']?accessToken=None
How do I get my DARWIN_KEY var into the actual code so that it can be used in a request? I originally had it in a separate python file but this isn't the proper way to do things on heroku apparently
isn't it os.environ.get
PORT = int(os.environ.get("PORT",5000)) is a line I'm using in my app
so no need for the str() either?
the PORT = and DEBUG = lines are fine
just move the app.run() to the bottom and replace the current app.run() line with it
oh wait
sorry i left for a sec didnt rwealize separate project haha
I'm so sorry lol, I was sitting here waiting for a quiet moment to ask my question lol
flask is throwing the 500 or that api you are calling
print out that url string before you pass it to requests.get
make sure its what it should be
youre doin ga lot of url + url + url + token etc stuff
the issue is clearly with the request itself
oh dammit I pasted in the same code twice, lemme edit
There, edited my original question
I believe that means that it's seeing the request as having accessToken equal to None?
@junior cloak think you can help with getting my db up and running on heroku as well?
wait now my app isn't deploying anymore. It says my requirements file is bad
I added the marshmallow_sqlalchemy module to requirements.txt and then it wouldn't deploy. I took it off and I'm still getting the same error...
.title2 {
position: relative;
float:right;
color: white;
margin-right: 5vw;
margin-top: 10vh;
font: 400 7vh/1.2 "Century Gothic";
}
.text2 {
font: 400 2.3vh/1.2 "Century Gothic";
position: relative;
color: darkgray;
word-wrap: break-word;
text-align: right;
float: right;
margin-top: 1vh;
margin-right: 5vw;
width: 30vw
}
Any idea how to get that text below that title?
can I see the HTML too?
<div class="second">
<img class="side" src="images/image1.png">
<img class="line2" src="images/liner.svg">
<h2 class="title2">What we do</h2>
<p class="text2">
Ewan Skinner LTD Plant Hire was established in 2014 and is based in Inverness; the capital of the Scottish Highlands.
We are a family run company providing plant with operator hire in both the commercial and private sector.
</p>
<a class="findlink" href="./about/index.html">Find out more</a>
</div>
Your a web-dev moving to python. I'm a python dev moving to web-dev xD
Put the h2 and a p in a div or something and use display flex, flex-direction column
Yeah something like that haha
My requirements.txt file is broken now
@tacit orbit dont add it to requirements.txt. you shouldnt need to ever manually modify requirements.txt
np!
@tacit orbit are you doing the flask app from inside a virtual environment
yeah
use docker
no
then pip freeze > requirements.txt is what you do to generate requirements.txt
from pip
so first just pip install whatever-package-you-need
and then freeze it
Use pipenv
the packages will have other dependencies that pip freeze will find
i use pipenv but at present i'm just trying to help him
get the code running
he has a deadline and doesnt need to switch all his tooling quite yet
but yes, i swear by pipenv
Shame pipenv in docker is not great
So I just did that and it's not working still
does it run locally or not
I was going to try reverting to a previous commit but I don't know how to do that
@junior cloak its so slow
it does
@tacit orbit what is the error? and does it run locally? you should not need to revert
just post the error
it runs locally
post the heroku error
oof greater than 2k character
@shrewd sand do you normally use the alpine images or something? the pipenv image is based off the full debian python image
@brave karma i like smaller images as well so even then my dockerfile to bootstrap a pipenv project is like 5 lines
@junior cloak i did not think of that...
use a debian image
It might be faster
Interesting
no the pipenv image is the debian image
i just dont know what you mean by "slow"
other than everything in docker is going to be slower a bit than non-docker
and if you are on a mac or windows even more so
@tacit orbit there is some problem with that package, bonjour-py==0.3. i cant install it either. do you know why it's in your requirements?
@tacit orbit please pastebin the requirements.txt
no idea
my requirements went from like 10 lines to 66
What
okay so you probabbly were not using the virtual environment
I'm in my venv
@brave karma sorry wrong tag
Oh u meant the other guy
yeah sorry
np
@tacit orbit "in it" as in in the folder, or you sourced the venv activate script
what does it say in the terminal if you do which pip
/usr/local/bin/pip
... yeah i think something is up with your shell
that is not the venv pip
what about which python
/usr/bin/python
yeah those are both system versions
not the virtualenv versions
so your requirements.txt has your system packages in it
weird
oh wait when we generated the requirements file before I think we did like pip freeze -r > requirements.txt
or something
not the folder venv right?
not sure why your shell is being weird, but in the meantime you can run it manually
nah
yeah that gave me all the system files
not from inside the venv folder but with the venv sourced
yeah.
so your venv is not working basically.
fun times T_T
so heres what you can do first
before fixing that
wherever the venv folder is actually, you can run pip manually because its copy lives in theres
venv/bin/pip
replace venv with path of the actual venv
do I source it?
no just replace the pip command with it. like
so see what venv/bin/pip freeze > requirements.txt does
sourcing the venv is just a shortcut for that
it is suppposed to replace python with the one in side the venv bin folder. same with pip
no such file or directory
what is the path you are giving it
take out 'venv' and replace it with the path to the actual folder were you put the virtualenv
from system root or the root directory of the project
like
the venv is literally just in my project
I've tried both btw
what is the name of the venv in your project root
the folder
venv or something else
venv
if you have this command, pastebiin the output of tree -faL 3
or paste here
from inside your project root
where you think the venv is
no dice 😦
great. okay well
lol...
yeah
and inside the bin folder is python and pip
yup
this is correct?
yes
no such file or directory
(venv) ryanMatthews (ryan-matthews *) labspt2-scratch-and-map $ ./venv/bin/pip
-bash: ./venv/bin/pip: /Users/ryanMatthews/Desktop/lambdaSchool/labspt2-scratch-and-map/scratch-and-m: bad interpreter: No such file or directory
bad interpreter
okay so your virtual environment isjust kind of screwed basically
haha
tada
Thanks so much for the help my dude
We've been taught a lot of stuff but we haven't been taught anything about python and I was like "yo lets use python/flask for our backend since it would look really good on our resumes to be like we learned this in 10 weeks for a fully functional app"
one sec
biting me in the ass
So I've tested my original flask app, and the jsonToken variable seems to be working fine
For some reason, I can't get the key working as a var in heroku itself it seems
To reiterate: I've got my API token set as DARWIN_KEY config variable as such:
app = Flask(__name__)
DARWIN_KEY = os.getenv('SECRET_KEY')
Here is my request:
response = requests.get("https://huxley.apphb.com/all/" + str(departure_station) + "/to/" + str(arrival_station) + "/" + str(user_time), params={"accessToken": DARWIN_KEY})
But I keep getting the following error:
2019-03-07T20:10:34.195763+00:00 app[web.1]: requests.exceptions.HTTPError: 500 Server Error: Internal Server Error for url: https://huxley.apphb.com/all/tth/to/ecr/['0821',%20'0853',%20'2147']?accessToken=None
But the request itself is fine when I test it in flask itself
can someone tell me why this doesn't work ```@app.route('/youtube-dl/q', methods=['GET'])
def q_size():
content = {"success": True, "size": json.dumps(list(dl_q.queue))}
return jsonify(content)
because it returns this
"size": "[[\"https://www.youtube.com/watch?v=2B6UvU-B7X4\", {\"format\": \"bestvideo\"}], [\"https://www.youtube.com/watch?v=5mejPwXXAdk\", {\"format\": \"bestvideo\"}], [\"https://www.youtube.com/watch?v=5mejPwXXAdk\", {\"format\": \"bestvideo\"}], [\"https://www.youtube.com/watch?v=5mejPwXXAdk\", {\"format\": \"bestvideo\"}]]",
"success": true
}```
@orchid aspen do you just mean the ugly formatting?
on line 3, you are turning the size stuff into json
and then on line 4 youre doing it again
Is there a way to align two divs side by side without it misaligned with line breaks?
python vs js for web dev
Why not both?
Yeah, I'm taking a course on udemy right now that will teach me both.... but its going to focus on python and django.
was just curious why is java more popular?
Java or JS?
sorry JS is mainly used for web dev yes?
Correct. It’s popular because it’s kind of the only language of the browser at the moment
You can get by without it using only markups like html but to add interactions you’ll need JavaScript
So instead of JavaScript vs python it’s more of should I use JavaScript in my web project since they’re sort of unrelated
I see, so Javascript is whats used for user accessibility