#web-development
2 messages Β· Page 60 of 1
sorry for being borring
i am pushing it so much in order to get better understanding of flask
title=post_opens.title
What does your class form look like?
What you can do is create a list of title, content, author and send it in render_templates. Then access the list with index in html
@nimble star you mean thing where i create posts?
<h2>Create New Blog Post:</h2>
<form action='/posts' method='POST'>
Title: <input type='text' name='title' id='title'>
<br>
Author: <input type='text' name='author' id='author'>
<br>
Post: <input type='text' name='content' id='content'>
<br>
<input type='submit' value='Post'>
</form>
<hr>```
or db?
class BlogPost(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(72), nullable=False)
content = db.Column(db.Text, nullable=False)
author = db.Column(db.String(20), nullable=False, default='N/A')
date_posted = db.Column(
db.DateTime, nullable=False, default=datetime.utcnow)
@drifting bison uh i am trying to get it from database
if someone knows the answer please ping me
@fickle fox I'm not sure about this, since I don't handle my forms this way on flask, but it seems strange that your action attribute points to /posts when your route is /posts/post/<id>
I think you don't get any data because the data from your form is not sent to the correct route
oh its for creating in something called posts, this one is post
again if someone knows what th eprob ping me
oh i dont have log in system yet
author is input field where they type name
Hey @knotty seal!
It looks like you tried to attach file type(s) that we do not allow (.webm). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .m4v, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg.
Feel free to ask in #community-meta if you think this is a mistake.
Hello, could someone help me create a site with Python? ^^ Come in a private message if you don't mind ^^
Nobody is going to personally train you
If you have a question, then ask it here
but you need to show some effort
and willingness to learn on your own
Okay, thank you, I'm going to start now ^^
Hoping this is the right spot, but i've got a ruby mechanize script i'm converting that will let me log into a webpage and do some automation from there. When i use postman and 'get' the url, i see everything. When i try it by doing
page = requests.get(url)
page.content is just giving me a py/64
i'm pretty sure that's part of the request (image in the header or something?), but it seems to be all it's getting back. Is there some way to skip that and just get the body or am I doing something wrong. I've been digging through docs for awhile now and it all seems to say it shoudl be working, and I can do their examples fine
to add, the only thing i've seen that might make sense is that i may need to use selenium, but i'm trying to avoid that as the original ruby script doesn't seem to be actually using a browser(i'm unsure as i don't really know ruby) and in my testing with it i found i was having to add a ton of conditional code to detect when the page actually loaded
Have any of you used vuejs with flask? This is the code i have:
<html lang="en"><head>
</head>
<body>
<div id="app"><p>{{ message }}</p></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<script>
var vue = new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
}
})
</script>
</body></html>
but its not doing anything
but if i open the html file in a browser without flask it works fine
I've tried that once, didn't work. Glad I am not alone.
Thought I am too stupid to try Vue
Guess the better way here is to have two vhosts
ugh
one for vue, one for flask rest
i dont really want to do that
i have another website using vuejs i guess i can just add it to that one
on your pc, you can do flask with werkzeug and the static html with py -m http.server for a quick setup
But I really don't get why this does not work
Werkzeug should serve the html as it is if there is no jinja blocks in it
with render_template
alright, ill look into that. How can i read all the html data as a string and then return that? because it looks like returning html data without render_template works for other stuff
don't mix templating and vue
if you use flask with vue, output json, not html
that is the whole point of vue
having an independent frontend and a rest backend
oh ok
i guess that makes sense
i was just trying to avoid having to have 2 ports open
nvm that was stupid π
but you can solve it with a subdomain
so it was not stupid
sometimes my brain is a mess
rest.example.com and example.com, only 443 open
how so?
i really like vuejs, and i want to learn more python which is why i chose to do it all in flask, i already have a restapi in nodejs running and other vuejs website, so it would kinda be better to incorperate it all in that
true
I need help to make this part of the most beautiful tables(MESAS), which is in the final design.
ok, i really don't want to use selenium to connect to a website and automate it as it seems to be insanely slow since it's actually loading a browser, even headless. I know somehow someone used ruby + mechanize to do it, but i can't seem to replicate this at all as everytime i hit the site with anything else i just get garbage back
is there a way to trigger alert to someone else? like... if i ban someone on website... so he get notification with it.. and it will signout his account? if yes please pm me...
Is it worth learning Kotlin for Mobile app development if you know web development but also want an app of your website.
Either Kotlin or Swift
anyone know how to get apache2 running python scripts? i followed this https://www.digitalocean.com/community/tutorials/how-to-set-up-an-apache-mysql-and-python-lamp-server-without-frameworks-on-ubuntu-14-04 and am getting nowhere
<VirtualHost *:80>
<Directory /var/www/html>
Options +ExecCGI
</Directory>
AddHandler cgi-script .py
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
#ServerName www.example.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
RewriteEngine on
RewriteCond %{SERVER_NAME} =www.mysite.xyz
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>
thats my /etc/apache2/sites-enabled/000-default.conf
most of it except the top is default, and I didnt change the directory index, cuz it already defaults to index.py
the test.py file, in root, is mode 755, and it's just printing the raw python
if anyone has any advice, needs more info, @ me. thanks :3
edit:
restarting apache2 is giving no errors, and nothing shows up in /var/logs/apache2/error.log
and this is my python script
#!/usr/bin/python
import cgitb
cgitb.enable()
print("Content-Type: text/html")
print()
print(3)
import requests
import re
headers={
'Host': 'www.instagram.com',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0',
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'X-CSRFToken': '****',
'X-Instagram-AJAX': '****',
'X-IG-App-ID': '****',
'X-IG-WWW-Claim': '****',
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest',
'Connection': 'close',
'Cookie': '****',
'Content-Length': '0'
}
uid = '*****'
r = requests.post(f"https://www.instagram.com/web/friendships/{uid}/follow/", headers=headers)
print(r.status_code, r.reason)
print (r.headers)
I can send a follow req with same headers from burpsuite but here its giving me 403 ;-;
!code @warm spire
Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.
To do this, use the following method:
```python
print('Hello world!')
```
Note:
β’ These are backticks, not quotes. Backticks can usually be found on the tilde key.
β’ You can also use py as the language instead of python
β’ The language must be on the first line next to the backticks with no space between them
This will result in the following:
print('Hello world!')
please format your code as shown above
ty :3
who knows django?
Anyone familiar with storing media files on s3 and then displaying them
Hey friends. Can anyone guide me to a better example of how to input data when using the many-to-many relationships here.
https://flask-sqlalchemy.palletsprojects.com/en/2.x/models/
would i just append tags to Page.tags.append('some-tag') and then commit?
Or would it be:
Page.tags.append(Tag())
hey!
any DRF specialists in here? π
hey guys
i installed pillow with pip install pillow
it says it is installed but doing from PIL import ImageOps
it says no module named PIL
@cloud path, maybe check the version with pip show Pillow?
it says that
mm
looks like it is in a different path
from the path in which i'm working
it is strange because ucp path was my old project
now i'm on another project with the venv enabled but when i install it, it got installed in the ucp path
that is the old project
@cold anchor Thanks a ton bro! Python works like a charm
1 core
with cpu load of 0.8%
It was able to handle 10K concurrent websocket connections
All I did was change the open files limit
Memory usage is also low
I'm pretty sure it would get as high as 50K in a single server
I also seperated the NLP and the API layer
@zealous siren
Thank you so much for your kind advice @cold anchor @zealous siren
π―
π glad you got it working!
Cool
literally never used Python before. just here to ask if it were possible, and what I'd need, to be able to have a program which checks for a list of text on an open Google Chrome application matches text from a list, and if so, it presses a button
Autohotkey is better suited for that
AHK can search for text on Google Chrome?
hmmmmmm
In any event, this channel is for web development, not automation
oh sorry, I thought this was related
Hello guys. I'm new to web dev and currently programming basic web cgi's from flask.
I don't know HTML so what is the best tool to kinda design the web-page and then it gives you the HTML output.
And can you suggest me the best tutorial series.
I want to learn Flask for the fundemantels before moving on to Django so i can get the basics right and make better websites.
Learn HTML
this is the only answer
You are also not programming servers, you are programming a cgi
@native tide
Also, learning Flask to be better at Django is the wrong approach
if you want to be good at Django, use Django
@tired root Wow. Thanks a lot for the answer and for correcting me. I'll learn HTML then.
π
"Common Gateway Interface" is that what you mean with cgi.
WYSIWIG with HTML has been tried, it has failed, any sort of visual editor just does not get it right
Yes, the python variant is called wsgi though
but it is essentially the same
It's a program called by the web server which returns html and http status codes and gives it to the web server
no
In computing, Common Gateway Interface (CGI) is an interface specification for web servers to execute programs like console applications (also called command-line interface programs) running on a server that generates web pages dynamically. Such programs are known as CGI scrip...
The web server , such as apache or nginx, handle the connections and route them to your application
Oh ok
Your application handles returning status codes and contents
I have written an app that does the following...
I wanted some advice on where I need to go from here...
turn left
What do you want us to say? We do not know what your plan is there, but I doubt people are going to order coffee over the internet
I made the video just to show some folks.
Also, it won't be used on mobile.
What I need to do is figure out how to have multiple people in an office use this to order.
It will be an app purely for people in my office.
Yes. So let's say 10 people make an order. Do I send that data to a database and compile the order into one long one
Someone needs an interface to check the orders and get them for the people
But are your co-workers that damn lazy so they can't go to the coffee maker themselves?
It's for a coffee shop. Not an in-house coffee maker.
And covid-19. So the fewer people the better
Then look for a way to integrate it into the POS
Or just use a tablet to display the current orders that servers can look at
in any event, you need a web server
Staff will be paying me - or another person in the office. We will pay the shop via credit card or whatevs.
Depending on the volume of the cafe, a simple RasPi may be enough
Apache 2.4 with mod_wsgi and a database
Heh. I just got my raspi from my parent's home
Using a Pi4 with 2gb ram may be benefitial
I can use pythonanywhere
You really want to restrict this to LAN
Not possible. Government has locked the systems down tighter than a goldfish's arsehole
what?
It is a government office
Does anyone know if its possible to send in 2 arguments, like the below pic, in a URL call in django?
Anyway, at this point my only answer is: Talk to the administrator. I am not going to help anymore
I work for the government in an office. We have a cafe we order from. I want people to order on this app between say 7am and 9.30 am. Once 9.30am hits, I send the order to the coffee shop. They make 10-20 coffees and deliver them.
Okay.
They don't need to want this. The network doesn't matter. This is a web page that people in my office will place an order on. That order will be sent to the coffee shop. By email perhaps.
Anyway. Thanks for trying to help.
then you need to store orders in database and load that on page load
right, so how can i take in the 2 arguments and pass them to the function params
yes
How?
ah sorry xD
lol
right, thats the function parameters, but how do i get it to go into the path from the form.
how does your path look?
path('subsnack/int:person_pk/int:snack_pk', ...
don't forget the slash
sorry i'm french i'm not good in english x)
thats okay haha
did I answer you well?
yes, i had it like this before with the /
but it gave me and noreverse match error
Got it! thank you @tardy schooner, the error was in the html
Hey guys, currently have code that uses gspread to input data from Riot API (League of Legends) into a Google Sheet
Right now it's pinging the API once per cell -- looking to have it do it once per row, or table, so I don't max out after every game input
Can anyone help?
I am trying to build a desktop app for webpage. They don't have an API. So I have revrse engineered the network requests and built the app.... But there is one request that uses vue js on the frontend to dynamically generate the data based on filters chosen which I am not able to understand how.... So, I'm planning to load up the webpage on the app, let the user build the filter and capture the data that is being posted. Is it possible? If yes, how can I do it?
does their ToS allow this? if not, we unfortunately can't help with that
Yes. I have mailed them about it. They have said as long as it within their rate limits, it's going to be fine
I'm not sure about the platform you're using to develop specifically, but most desktop app builders have a way to "frame" a browser window, you could use that
not sure about "capture the data that is being posted", that's some serious security stuff you'd probably have to get around
The data to be posted is processed on the frontend so nothing serious about the security. It's just a bunch of filters that enable/disable other based on values and built into a final query
when messing with these filters on your browser doesn't help you figure out how to construct the filters?
@cold anchor Keeping open files to 50K does increase it to 28K concurrent connections
But what exactly is this open files limit
what's it job and does it affect any other functions maybe security
Tried google but no proper source for the max open file feature
a big part of its job is to prevent a user from accidentally opening a bajillion files
i have a general question and wasnt sure where to really start looking to learn about it. Say the site actual url is url.com/WorldWarTwo. If someone types in url.com/WWII, how does it know to redirect to the right link
You can write redirects with .htaccess rules if you are using apache
or simply have a second alternative route when using flask
@app.route("/WWII")
@app.route("/WorldWarTwo")
def ww2():
pass```
ah i see you'd predict/write the case exceptions you want to recognize and then feed it through what u actually want. Ok ty i know where to star tlooking
The W3C standard requires case sensitive routes, keep that in mind
so adding more rules for lower and upper case violates that
thanks m8 π
@app.route('/dashboard')
def dashboard():
return render_template('dashboard.html', legacy=legacy)
```I have something like this in my code, I cut it shorter so its easier to see what I want to do but
`legacy` is a variable referring to a discord bot. Currently to do this I use threads and run both the website and the bot in the same application just on different threads. That doesnt work on linux so I need to make the website get data from my bot over HTTP. How would I have my bot send data to this dashboard view?
Hi all
Question:
Let's say I wanted to work with an API or sorts, and the data would be returned in JSON format as most APIs do.
If I wanted to make a dashboard of data taht is to be fair, very structured, is it better to use SQL or noSQL? What would be easier to work with in the long run? Im using Flask btw
SQL most likely
I got this error trying to make an upload page to my blog project. Anyone know what is causing it?
Here is the code:
def createPost():
if request.method == "POST":
title = request.form["title"]
subtitle = request.form["subtitle"]
category = request.form["category"]
content = request.form["content"]
if request.files:
banner = request.files['banner']
if banner.filename == "":
flash('Image need a name!')
return render_template('admin/createPost.html')
banner.save(os.path.join(os.path.dirname(__file__)) + '\\static\\img\\banners', banner.filename)
post = Posts(title=title, subtitle=subtitle, category=category, content=content, author="Test",
date_posted=date.today(), banner='static\\img\\banners' + banner.filename)
db.session.add(post)
db.session.commit()
flash('Posted with sucess!')
return render_template('admin/createPost.html')
@knotty seal how about and sms or email notification?
what library should I use to put a string gotten from some python code (like some scraped data) onto a website?
Beautiful Soup
I mean like displaying the data on a site
you mean
maybe? I just want to display a number I got from scraping onto my site
u can do it with for loop i think
@app.route('/post/<int:id>', methods=['GET', 'POST'])
def post_open(id):
post_opens = BlogPost.query.get_or_404(id)
if request.method == 'POST':
post_opens.title = request.form['title']
post_opens.content = request.form['content']
post_opens.author = request.form['author']
return render_template(
'post.html',
title=post_opens.title,
content=post_opens.content,
author=post_opens.author)
else:
return render_template('posts.html')```
anyone knows why i cant get values from selected id in db
{% block head %}
<title>{{ titile }}</title>
{% endblock %}
{% block body %}
<div class="cent">
<p name ='title' id='title'>{{ title }}</p>
<br/>
<p name = 'content' id='content'>{{ content }}</p>
<br/>
<p name = 'author' id='author'>{{ author }}</p>
</div>
{% endblock %}```This is where i want them to display
i can see page i see body's css (bg is red color)
but i cant see text i want
can i create online game in django?
if someone knows the answer on my question just ping me
@regal bane this error appears when you do t have the proper rights to access that file in your system. Need to chmod it. Your code is probably fine
@fickle fox did you try to print the values and check if youβre actually receiving anything from your request?
Good evening everybody. I'm having trouble finding tags in beautiful soup. Is there a way to find a tag (to then move to the other ones in the parse tree) by looking for it's string content rather than it's id/class/name/etc?
<td>
this is the string I wanna search for
</td>
For instance, if I wanna find that particular td tag by looking for "this is the string I wanna search for", how should I proceed?
If u mean like get only one at one time and store them separately i would do it with for loop
No, it goes like this:
<td>
MyString1
</td>
<td class="numero"> A specific value related to MyString1</td>
<td class="numero"> A specific value related to MyString1</td>
<td class="numero"> A specific value related to MyString1</td>
<td class="numero"> A specific value related to MyString1</td>
<td>
MyString2
</td>
<td>
<td class="numero"> A specific value related to MyString2</td>
<td class="numero"> A specific value related to MyString2</td>
<td class="numero"> A specific value related to MyString2</td>
The site is structered like that. So my idea was to find the "td" that contains "MyString1" and from there move down to one of those specific values (they're just numbers).
self.big_div = self.soup.find("table", id = "container_table").find("td")
if str.__contains__(self.big_div.text,"MyString1")
I tried that to check and see if the table that holds those "td" contains the string I'm interested in. But that doesn't help because doesn't return the tag itself.
i have one question but no one answers me
the answerers get tired of answering lol
can i create online game in django?
@velvet vale Yes, you can use django channels to make the connections. Google it and you probably find some tutorials
I never tried myself, but already saw something about
@cold anchor yes, I tried but there are lot of filters and im not able to hardcode, I have also found the js code(vue.js) responsible for it.... I have no experience with Js and I'm not able understand it
Hi.. is there some way to trigger script on another user? For example, i click on button on my site and someone else get alert + it will run some script?
sure, if you send them something via sockets
so sockets could do it?
Click button -> send data to server -> send data to user
but they'd need to be connected with sockets all the time
I'd just do a flash on reload
if using flask
Me too
Add the pending flash to the db, flash it when the user refreshes
but if i want to 'pause' another account, they can do whatever they want until they refresh session
pause? you mean ban?
something like that :'D
What are you trying to do?
just that if i press as admin that 'ban' button, so it will logout his account
This will only work on refresh
damn it :'D
If you are using js a lot, have js pull the data every couple events
yea... thats issue.. i never used js :'D soo i wanted to know if there is a way in python itself
The issue isn't python, your issue is with http
but if there are no dynamic javascript elements, every action is a refresh
so all the user can do is look at the page
when he refreshes and is banned, it should lock him out
you can strengthen that by using database sessions and delete the session
How do I use Google OAuth with aiohttp?
Learn how Oauth works, learn how aiohttp works, then follow the standard
I found a lot of libraries for that
Should I use one of them or it is better without them?
If you can't answer that question then you shouldn't be messing with peoples google accounts
I need only their email
Some mistakes can leak tokens, that give others access to those accounts in your name
and that is a very bad thing
If you only want the email, use a form
You need to phrase things better, to say what you want. So you want to use OAuth, but if you have no clue about it, it is not advisable to use it
because of reasons I've mentioned earlier
This is not something to be taken lightly
Yes, they will need to enter a password, but I'd rather have my account on a shitty site hacked than my gmail oauth tokens
My school has google suite with custom domain, emails are formed like {second_name}{first_name[0]}{year_of_graduation}@domain.com. Our class is planning a competition and it's only for students from 7 and 8 grades. I want people to login on the competition website using their GSuite email so it is easier to check whether they have permission to access the tasks. What should I use for that then?
hey guys, is it possible to create in flask column in db with boolean value?
@fickle fox yes it is
yourbool = db.Column(db.Boolean, default=False)
can i set deagult value to be false?
yes you can
{% block main %}
{% if user == "manager" %}
<h2>Manager Login</h2>
{% else %}
<h2>Student Login</h2>
{% endif %}
<form action="/{{ user }}/login" method="post">
{{ login_form.csrf_token }}
<div class="form-group">
{{ login_form.email }}
</div>
<div class="form-group">
{{ login_form.password }}
</div>
{% if login_form.errors %}
{{ login_form.errors }}
{% endif %}
<button class="btn btn-primary" type="submit">Log In</button>
</form>
{% endblock %}
I don't understand
hmm so how can i check in jinja if value from db is true or false and to display them differently?
{% if some.value %}
print some value
{% endif %}
John Meow, there are libraries to handle OAuth and donβt worry, token leak from your site wonβt hurt anything.
except your site
https://discordapp.com/channels/267624335836053506/366673702533988363/711217658485538856 why am I getting csrf tokens don't match?
I'm using brave browser
Do I need
from flask_wtf import CsrfProtect csrf = CsrfProtect()
thanks scorcher
I'm combining a Django DetailView with a UserPassesTestMixin to implement a user-owns-object check, but I'm not sure how to avoid multiple calls to the database. Any thoughts?
i need to send jobs to my discord bot from my sanic app via python rq
or celery
idk how i should do it
I'm using icons from font-awesome, I have made a website using icons using only static HTML, JS and CSS. I'm converting this website into Jinja2 and Flask.
tl;dr; My icons are showing up on the static site, but not the flask site
Can someone helps me with my Django project?
when i start server get that error
https://i.imgur.com/dYe6Vtm.png
I cant connect base.html with my static files
using that syntax <link rel="stylesheet" type="text/css" href="{% static 'style/style.css' %}">
Here is my settings.py some code:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file)))
PROJECT_ROOT = os.path.dirname(file)
sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
Here is project structure:
https://i.imgur.com/n60Rgg3.png
did you try it without the static? Because you're mentioning static twice. Once in the STATIC_ROOT and another one in the STATIC_URL. I'm saying this as a Python dev but a noob in Django.
STATIC_URL = '/'
I have some data science / machine learning Jupyter notebooks that I'd like to turn into webpages. I'd like to embed them into a site but they need a running kernel and trained models to function. What should I be looking into?
I really need help understanding formsets and whether or I even need them. I have several CARDS from bootstrap displayed and I have a 1-5 dropdown on each box. There isn't a lot of tutorials or examples on this and my favorite book two-scoops leaves out formsets for the most part.
Do I need formset to display 10 cards all with their unique form that when changed will make them work? I am not interested in using the prebuilt rating apps, I want to understand this myself with Django.
Hi, I'm building a Flask app and every time I have a new code change have to quit flask run in the command line and restart the server. Is there a way to get live changes in the browser so I don't have to stop and restart?
yes
add this
if __name__ == '__main__':
app.run(debug=True)
at the end of the initial .py file
and run from cmd python myflaskproject.py
and let the cmd open
@half bough
Hi @limber spade Thank you! I was literally just reading about this on Stack Overflow.
I'll give it a try!
np
Anyone profficient in Django? I am really stuck on formsets....and if I even need them?
I have these cards, I added a dropdown rating using a form but I can't get it to update. I am not sure how to add ratings to objects. The city shouldn't be changeable, is there a way to auto populate the city to be that of the card? Hopefully someone can help
does anyone know if this is okay for a simple login page? when I hit the submit button nothing happens.
looks like this:
does getting help with bs4 fit here? π€
are there any web hosts in particular that make it easier to host flask apps?
is pythonanywhere a good choice
yes I use pythonanywhere
for my application backend, it's very cool
I was even able to add the autoupdate from github thing that other providers offer
if you end up wanting to do something similar, you want to do this https://medium.com/@aadibajpai/deploying-to-pythonanywhere-via-github-6f967956e664
Also form method = 'POST'
@native tide Thank you so much. hidden tag was missing.
hey can anyone explain to me like in what ways you would use RESTful api's
im having trouble understanding the concept
how could i add administrator capabilities to add a question set on my website
so it creates a new json file
This is django btw.
So below is a demonstration of a simple search filter.
The search filter works by using this views function.
def computer_details(request):
results = Computer.objects.order_by('users_name')
title='list of all computer'
form = ComputerSearchForm(request.POST or None)
context = {
'list_widgets': results,
'title': title,
'form': form,
}
if request.method == 'POST':
results = Computer.objects.all().order_by('computer_name').filter(computer_name__icontains=form['computer_name'].value())
context = {
'list_widgets': results,
"title": title,
"form": form,
}
return render(request, 'week6_app/searchrecords.html',context)```
Wondering if i can somehow modify user input to delete a record based on id. So if user enter 1 it will delete acer (referring to the image above)
I have this seperate delete function that works with a seperate form on a different html page.
```python
def delete_view(request, id):
obj = get_object_or_404(Computer, id=id)
if request.method=='POST':
obj.delete()
return redirect('../')
context = {
"Object": obj
}
return render(request, 'week6_app/delete.html', context)
I'm wondering what you would use as the http response for, "I have received your POST request, bu the server has determined that something is wrong with the data being sent or you manipulated it."
hmm
How would i change in db if something is true or false
Depends on what youre using
oh i created db with flask adn sql alchemy
i am trying to make something like pinned posts
Well, I can't speak to that, but to mark a boolean, you would ahve a boolean field in Post You would do something like
post = Post.query.get(1)
post.pinned = True
db.session.add(post)
db.session.commit(post)
i will try that thanks
how to use elif with jinja?
{% for post in posts %}
<div class="pin">
{% if post.pinn.True %}
<h2>jestee</h2>
<h2>{{ post.title }}</h2>
{% if post.author %}
<h3>By: {{ post.author }}</h3>
{% else %}
<h3>By: N/A</h3>
{% endif %}
</div></div>
{% else %}
<div class="unpin">
<h2>{{ post.title }}</h2>
{% if post.author %}
<h3>By: {{ post.author }}</h3>
{% else %}
<h3>By: N/A</h3>
{% endif %}
{% endif %}
{% endfor %}
</div>```
cuz i am trying to do it like this
@app.route('/posts/pinn/<int:id>')
def pinn(id):
post = BlogPost.query.get_or_404(id)
if request.method == 'POST':
if post.pinn is True:
post.pinn = False
db.session.comite()
elif post.pinn is False:
post.pinn = True
db.session.comite()
else:
pass
else:
return redirect('/posts')
but its always sticked, i mean every post
now i have error post in undefined
{% block head %}
<title>Posts</title>
{% endblock %}
{% block body %}
<h1>All Posts</h1>
<hr>
<h2>Create New Blog Post:</h2>
<form action='/posts' method='POST'>
Title: <input type='text' name='title' id='title'>
<br>
Author: <input type='text' name='author' id='author'>
<br>
Post: <input type='text' name='content' id='content'>
<br>
<input type='submit' value='Post'>
</form>
<hr>
<div class="pin">
{% for post in posts if post.pinn.True %}
<h2>{{ post.title }}</h2>
{% if post.author %}
<h3>By: {{ post.author }}</h3>
{% else %}
<h3>By: N/A</h3>
{% endif %}
<p>{{ post.content }}
</p>
</div>
{% else %}
<div class="unpin">
<h2>{{ post.title }}</h2>
{% if post.author %}
<h3>By: {{ post.author }}</h3>
{% else %}
<h3>By: N/A</h3>
{% endif %}
<p>{{ post.content }}
</p>
{% endfor %}
</div>
<a href='/posts/delete/{{post.id}}'>Delete</a>
<a href='/posts/edit/{{post.id}}'>Edit</a>
<p id='time'>{{ post.date_posted }}</p>
<a id='open' href='/post/{{post.id}}'>Open post</a>
<a id='pinn' href='/posts/pinn/{{post.id}}'>Stick</a>
<hr>
{% endblock %}```
@app.route('/posts/pinn/<int:id>')
def pinn(id):
post = BlogPost.query.get_or_404(id)
if request.method == 'POST':
if post.pinn is True:
post.pinn = False
db.session.comite()
elif post.pinn is False:
post.pinn = True
db.session.comite()
else:
pass
else:
return redirect('/posts')
if anyone knows why ping me
commit() not comite()
Which do i need to learn earlier DjangoRestAPI or SQL??
SQL
@last hull SQL
@native tide @zealous siren Can you guys explain why? I need your opinion
@last hull see these both are totally different things and yeah it totally depends on what kind of implementation u are applying to. If it's a standalone where you need a database the SQL will be useful and if it's a Web App then REST API is the thing u need to dive into.
for some reason none of my css changes are showing up
@deft minnow can you please share the linking of css file?
all of the gradients, backgrounds, boxes, etc all are shown in the site. However, if I try to change something or even delete the file, my site looks the same
@native tide
Is it hosted on some server or u r trying this on local host?
local
Can you check the console of browser where the page might be showing any of error or warning by inspect element?@deft minnow
A cookie associated with a cross-site resource at http://google.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
(index):1 A cookie associated with a cross-site resource at https://google.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
nothing else
not sure if this has much to do with my code though, as I get it on other sites as well
@native tide
For the given error heres the solution i can try adding it to the response header: response.setHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Strict");
Not getting clearly what's the issue is with? U can DM me.
okay
@deft minnow hope i was able to help u in solving the issue.
When youβre creating a flask or Django app with a database do you normally build out the web forms and templates first or do you start with the database design?
hello, how do i change the color of the input box/ input text?
When youβre creating a flask or Django app with a database do you normally build out the web forms and templates first or do you start with the database design?
@half bough im a beginner but based on what i learned as of yet, you start with the basic templates, and then the database
Hi @limber spade are you building out a user registration form with a login? Iβm working on the same thing. Did you create your database last?
i havent created the full database yet
but yeah im working on the db now, after i made the framework
i think its called
Ok cool, thanks
SQL is used in more then just Web Dev
@native tide ehh its still undefined
im trying to get chromedriver to save cookies so i dont have to reenter my username and password any 1 got any ideas
if user and bcrypt.check_password_hash(user.password, form.password.data):
print("Hello")
login_user(user, remember=form.remember.data)
print("World")
return redirect(url_for('home'))```
I have followed a tutorial to get the workaround Flask and I am getting the error ``Flask has no attribute: login_manager``
login_manager = LoginManager()```
Located in my ``__init__.py`` file
In Django I am using a reset.css file but I dont want to keep copying the reset.css into every apps static folder location. Is there a way I can define a global css/static file?
@wicked tide hey sorry for ping, btw, after returning rendertemplate(...post=post), it says that sevres might be overloaded
guys, check this code:
<form class="form-group" method="POST" action="{{ url_for('send_email') }}">
I am using FlaskBlueprints, this HTML is inside the templates folder, inside the Blueprint Folder.
The problem is at action="{{ url_for('send_email') }}">
how to reference my bp?
sorry for interrupting btw, answer as you can
this is the error i'm getting :
werkzeug.routing.BuildError: Could not build url for endpoint 'olympo.send_email'. Did you mean 'olympo.delete' instead?
nevermind, i forgot to take my email function from main routes file.
-- closed
Hey guys, for Django, Iβm building a website that takes in a users address (but not storing it) and passing it to an external API to get some data. Is there any way for me to build this application in such way where I canβt access the customers data whatsoever
Like I canβt screen it
You have to use the name of your blueprint @wild thunder {{ url_for('name_of_blueprint.send_email') }} Otherwise it cant find the route.
hey @native tide !
thanks for the response but the error was actually that the route was not in my routes.py
hahah π
already solved
nevermind, i forgot to take my email function from main routes file.
@wild thunder
that's good.
what's difference default django and django (rest api)?
hello, I keep getting this error and I can't seem to find any solutions on stack overflow or on google
Error: The view accounts.views.change_password didn't return an HttpResponse object. It returned None instead.
I'm willing to provide full traceback and/or code if needed
thanks in advance
hello, I keep getting this error and I can't seem to find any solutions on stack overflow or on google
Error: The view accounts.views.change_password didn't return an HttpResponse object. It returned None instead.
I'm willing to provide full traceback and/or code if needed
@native tide Did you figure this out?
This is Django?
yeah, it's django
I didn't figure out though
here is the full traceback if you need it
ValueError at /account/change-password/
The view accounts.views.change_password didn't return an HttpResponse object. It returned None instead.
Request Method: POST
Request URL: http://127.0.0.1:8000/account/change-password/
Django Version: 3.0.5
Exception Type: ValueError
Exception Value:
The view accounts.views.change_password didn't return an HttpResponse object. It returned None instead.
Exception Location: C:\Users\\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py in _get_response, line 124
Python Executable: C:\Users\\AppData\Local\Programs\Python\Python38-32\python.exe
Python Version: 3.8.2
Python Path:
['C:\\Users\\\\Downloads\\Django\\Tutorial',
'C:\\Users\\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip',
'C:\\Users\\\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs',
'C:\\Users\\\\AppData\\Local\\Programs\\Python\\Python38-32\\lib',
'C:\\Users\\\\AppData\\Local\\Programs\\Python\\Python38-32',
'C:\\Users\\\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Users\\\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages']
Server time: Sun, 17 May 2020 22:21:39 +0000
So I have a few questions about the requests library and Im assuming since it has to do with web this is the place to post them.
-when and why would I use put, post, patch?
-and what would be the point to log in to a site or fill out a form on a site with a script that uses requests?
you use put, post, or patch if the website, or API, you're dealing with requires that you do that.
you log in or fill out a form if the web site requires that you do that π
yeah, it's django
@native tide
I lean on Flask and not Django but Iβll try to help.
Is change_password your function in your view? Or are they just default from Django?
So I have a few questions about the
requestslibrary and Im assuming since it has to do with web this is the place to post them.-when and why would I use put, post, patch?
-and what would be the point to log in to a site or fill out a form on a site with a script that uses requests?
@rose shadow
Search the web for HTTP verbs. I probably have a good bookmark I share with mentees, but donβt have access to share at the moment.
requests and other libraries combined with it are great for writing bots and spiders. Crawl a site, fill out a form or login, scrape the data, etc.
I have a Flask website runninng but I now want to expand the database to include a new model, how can I do that if I want to preserve everything else?
Are you using Flask-SQLalchemy?
yes
Search for Flask-SQLAlchemy migrations.
Sometimes just knowing the term to search for is hard. Iβm not just trying to pawn you off on google. π
Oh yeah, thanks. I have heard about django migrations but didn't think of Flask possibly having them
No, that's helpful. Sometimes you just can't put the words together, you know
Totally understand. Half of me helping people is helping them search the right thing.
Youβll see what you want to do is really easy.
Iβm just a good coder. But a phenomenal googler . (Iβve said that in an interview before haha).
Got hired so guess it worked. Heh. Good luck on the migration thing. Reach out if you get stuck.
Man, now I don't even know if I should learn Django too. The only other reason left is ecommerce capabilities. Based on what I have seen Flask isn't good at it. But maybe I'm wrong
I love flask. Django has too much in it for me. Too much magic.
True, but corey schafer has some fantastic tutorials for both
I can say this e-commerce though: make sure not to reinvent the wheel. Maybe consider offloading e-commerce bits to a backend you can wrap with your flask site.
I wouldnβt handroll an e-commerce site myself nowadays.
If I was doing it for myself I would probably stick to Flask, but it's for a potential job, so I'm kinda worried to screw up
Gotcha. Best of luck on it for sure.
Flask just matches my brain a bit better. Iβve always used lighter weight frameworks like this. Slim for PHP. And the little c# Iβve written is in NancyFX.
Versus the big boy frameworks.
I'm a pygame and Processing guy so I totally understand
just a quick follow up on migrations. I should create a separate migration.py file for it and then run on every machine? (I'm using git so I have it on local and remote)
@warm igloo ive used it for webscraping but ive recently decided to try to use it more for web automation and I have a few ideas but I just really need to clarify and bounce these off my head.
so I understand that I can login and fill forms out in requests but what would be the benefit of using a script? like thats the only part of that (filling forms out) im having trouble with cause I dont know why I should.
so just from what Im hearing, the only time I would post put and patch I should send data but when would I know or want to send the data?
when would I know the server can do something with post, put, patch data and how would I know what the server would do with it.
By reading their docs @rose shadow -- ultimately those verbs are convention. I make a post do lookup actions, I can make a PUT command do a deletion, etc. But I don't, cause I'm nice.
For instance, I've seen plenty APIs that never use anything but POST and GET. So if you sent a PUT, it would do nothing. Maybe it would send a BAD METHOD response, but only if they allowed it. They could make it do nothing at all.
If this is talking to a server you don't know, didn't make, don't have docs for ... well, you'll just have to try and see what happens. π
This is a decent breakdown of the verbs and when to use. But again, convention. π
HTTP methods tutorial on how to use them for RESTful API or Web Service.
okay thanks!!
Hey guys, has anyone seen an ide that lets you drag and drop html elements, and then builds the code on the side for you? It also does css as well, I can't remember what it's called but I remember seeing it in a youtube video.
can someone teach me something here?
@native tide you need help or wanna learn sth?
What you wanna learn?
Ok so you need help
Ive never done what youre doing may e someone will help ya
Yw
@native tide can you please explain what exact issue u r facing?
yes
my git hub is not working and im using it for the advanced EDx CS50 course wich I paid for. The team isn't repling
@native tide
You mean your repo or yr account?
no like thewhole thing
I can't do anything on it @native tide
Any ss if u can provide?
whats ss
I just turned 14 so im pretty new to discord
@native tide
ok thank you
I never knew of that thank you again
@native tide welcome
k cya latter
Did anyone used django crispyforms and have an opinion about it? It looks awfully complex to me and I feel I'm better with using Jinja macro's
Is it more useful to load data clientside or send the data with the initial sate? I am using flask.
Hello, hope everyone doing well,
So started using flask and didnβt go really far.
When i am supposed to create the database <python -m flask init-db>it throw me an error that says attribute error flask has no attribute open-resources,
I checked about circulaire import and googled it but got no answer if some one can help and explain how to resolve it it would be great thx
Quick question, I have a Flask blog where I pass my {{ post.content }} into a template, but it is always cast into a text, meaning if my post.content has something like <a href="#"> Link </a> it won't be interpeted as a link. But how can I make it interpretable?
{{{ post.content }}}
that doesn't tell me much, where did that error happen?
After I changed {{ to {{{
ah, I think I'm using syntax from another template engine
I think jinja is {{ post.content | safe }}
OH SHIT. You are a hero
It worked, thanks
A follow up. Does 'safe' imply it will be immune to some sort of html injection?
no, it implies that it's "safe" to render as HTML and you've taken care of the security concerns
gotcha! thanks again
I have been coding with Python for a while but I'm a pretty big noob when it comes to web development. I'm hosting a website through github. How do I add a theme/template?
hey what's up i have struggle in project ecomerce web app : i want to serve media folder that containe the image of the product and i didn't find how ple some one help and guid me
I think you're looking for static files
nope media file : django database store the product images in media folder
but django dont serve it
i host my website on heroku but did not display the images
Hey guys so Iβm implementing a Django website. In one model I want to be able to have multiple foreign keys that pertain to the same model. I know we can add multiple with the related_name attribute but is there a more sufficient way since the multiple foreign keys might not be all used
have you told django that its a static folder tho (or atleast) a folder to serve to
Could we have a one to many relationship, as a model can have many relationships to a foreign key
Well last time i checked (I havent used django for a while) Is it disables serving static files via the url in production.
An easy solution is use nginx to serve the media folder
thats django's static file thingy
and if i serve the media folder in nginx and host the app in heroku is that work ?
hhh yeh i know have two days searching to solve this problem and didnt find anything
how ?
You obviously need a second server, such as AWS or a VPS
then just add an A/AAAA record for example.com, pointing to the other IP via sub.example.com
virtual private server
Can you add a second vhost on heroku?
I've never worked with it, so..
I have my own root
I have my own root
@tired root you have your own server ?
From what I see from the Heroku docs, you can add subdomains
so just serve the static files with a subdomain, e.g. cdn.example.com
if you have a domain
or use whatever heroku gives you
There you go
nope static folder just for css js html and img but media folder is not in static folder it a separate folder , if i add another product in admin page , the product image store in media folder
media always changing it's not fix like static folder
@tired root
What shoud I use to definie this button? (There is no ID and class name doesnt work)
https://stackoverflow.com/questions/44999215/accessing-non-static-images-in-django
@tired root this work when debug = True
but i need a solution for deployment mode
@tired root
why class or id dont work ?
@steady ether Then just use a cdn
idk whats tripping you up
Seems like Django was the wrong choice for you
From how I see it, you simple upload them to media, then run collectstatic
and serve them from your cdn
well i dont think so im doing this project to add it on my portfolio
Hello, I'm currently making a simple covid site with flask. However, the numbers that the flask program gives do not update unless I tell my web host (pythonanywhere) to reload. Is there any way that I can make it so that my code runs every time someone visits the site?
How are the numbers updated? Only the routes that are visited are run, so maybe what you want is a cronjob
the numbers are taken from some python code I wrote to scrape some info from another site
then it returns a string
Oh ok, sorry. This is my first time making a public website, and I just assumed that it would run every time a user accessed the site if I put it in my mysite folder (it doesn't). I apologize for being unknowlegeable, don't really know a lot
I'm not entirely sure where to put this, but here seems appropriate.
Currently, I have a locally hosted d.py bot that's working quite nicely. I also am working on a website on that same server, which uses apache2. However, I want to add a login to discord button to my website (oauth2) so I can link connections on discord (since I believe that's the only way to retrieve connections). All the examples I've seen online use flask to run the webserver, but I wouldn't be sure how to move from apache2 to flask. What would be the best way to allow my d.py bot to access the oauth2 link?
apache2 runs flask with mod_wsgi
and you access remote uris with the requests library
pip3 install requests
import requests
oh okay, so i really shouldn't have to do much extra?
you need to modify your website to allow oauth
it has little to do with the bot actually
modifying the bot to spit out an oauth url is the smaller issue
implementing oauth to your website probably the bigger one
I would have a look at requests_oauthlib module
I was refering to the actual interaction but thats a point yh
haha yeah im trying my hand at web dev for the first time so its html
you saying for security reasons?
Him saying he is using html has little to do with having a webserver or not
maybe he should first build it, before thinking about infrastructure
testing is perfectly fine on http.server or werkzeug
im saying If you are just using Apache to just serve html files you might want to consider using an actual web backend e.g Flask (if you want to do py that is)
Flask is not a web backend
it's a wsgi library
@short pebble First thing you need to do, is to switch your web to flask or any other dynamic web language. But the question is, why do you need a login? Does it serve a purpose that makes the added responsibility worth it? and can you handle data in a way that is safe?
Because in most cases, a login is not even needed nor beneficial
But it adds a big workload and administrative strain
or something of the sort
okay ill look into flask then, thanks. well, for the most part, its the main purpose of the webserver. the only thing the login does is save discord identity and connections. I just need to get their discord id as well as their steam id.
why?
Are you trying to make a dashboard for your bot?
nope, i run a decently sized discord trading server where we would greatly benefit from added layers of security, i have to ban on average 5-10 scammers/bots per day
The principle of data scarcity is a good one so ask yourself if you really need those informations
I wouldnt go through the pain of Oauth login then
with a way to link discord/steam accounts, I can make the server more secure
No, you don't
just using Alt identifier that handles alts and scammers for you
^^
going through the pain of doing login with discord + setting up and deploying the site
wont stop people from joining
ive used alt identifier in the past, as well as SSO services like oneall, they work, but just not to our needs.
it sounds like you're trying todo exactly what alt identifier does lol
Discord and Steam Id's are an infinite free resource, checking against them does nothing, it only adds work on your side.
you'd be better off just turning on Extreme verification with discord lol
discord bots are not made to go to a website and login to steam and discord
and 98% of scammers wont be bothered
discord bots cant join servers on their own
then use Alt identifier lol
what you are describing is litterally what alt identifier does
i also doubt that the amount of scammers and self bots you encounter is more than average and makes it worth setting up an entire site for. And if it is above average then its probably likley that you're advertising your server in the wrong places.
they nearly all come from disboard
im also using the rest of the site not only as a way to learn html/css/js, but also as a portfolio for my projects.
so its not just the login page
@quick cargo Steam communities are often targeted, because of how stupid gamers are
They click on anything on the promise of a free game
yeah ikkkkk
yeah so many people fall for the stupidest scams
anyway
I use Discord Oauth on my site
it doesnt even touch html js css
and it is a massive pain to setup if you dont need it to link things
Its just janky with discord
i lost my internship this summer bc of the world ending, so this is my summer project haha
i got all the time in the world
tbf
if your system is just to make it tedious to have self bots get in or somthing
just make a command they have to use or somthing to get in
or just use a captcha bot
discord can you be any fucking slower -_-
yeah i used to have that too. having oauth is kind of 'industry' standard for cs trading servers nowadays
@short pebble https://paste.ofcode.org/bFd8knXGc7eQBzKBLZBMq2 this is my implementation of OAuth 2 for the Eve SSO API
maybe it helps you
It's still missing the jwt check though
okay yep any examples help, a lot of new things i do i'm just building off examples haha
class Discord:
@classmethod
@views.register_path(name="/login", classview=True)
def login_main(cls):
oauth = OAuth2Session(CLIENT_ID)
login_url, state = oauth.authorization_url(AUTHORIZE_URL)
session['state'] = state
return redirect(login_url)
@classmethod
@views.register_path(name="/oauth_callback", classview=True)
def oauth_callback(cls):
discord = OAuth2Session(CLIENT_ID, redirect_uri=REDIRECT_URL, state=session['state'], scope=SCOPES)
token = discord.fetch_token(TOKEN_URL, client_secret=CLIENT_SECRET, authorization_response=request.url)
session['discord_token'] = token
session['unique_id'] = str(uuid4())
return redirect('https://crunchy-bot.live/home') # todo redirect to profile```
thats mine lol
discord -_-
yeah well you are using a library, I am using requests
@short pebble I do that now with Game Login and Discord
I am doing it raw basically
You ask the bot to register, it generates 16 alphanumeric token for you, stash that information in database then sends you a link
you go to website, run through OAuth procedure with the game, and using that token, I tie your Discord ID and Game ID toether
yeah i mean thats pretty much all i need. i can already generate that token with my site, just was looking into tying it into my bot, since its the one that has to work with it
problem is signaling to the bot it needs to adjust roles, I'd consider researching Discord API and just tapping it manually for role assignment
it's not difficult at all
hmm okay, we'll see what i can do lol
token will come from the bot most likely
so you will need to look up that information
yeah, im sure once i get user login to website>discord bot retrieving token ill be able to figure it out
since i believe thats the hard part
Hi
in an api im using
Which means clients with good 100-Continue support are very nice to have
curl versions curl-7.19 and newer have excellent 100-continue support
curl versions curl-7.58 and newer need to add --location-trusted flag if you are including an Authorization header
How do i do 100-continue in requests http lib
100 is a status that the server send to the client, not the other way around
Well im getting some sort of issue with the Internet Archive API
wget works with Authorization, curl doesn't (but it does when using --location-trusted
With python requests http lib
I'm getting 403
and according to their API docs, they noted:
Archive is much more likely to issue 307 Location redirects than Amazon is.
Which means clients with good 100-Continue support are very nice to have
curl versions curl-7.19 and newer have excellent 100-continue support
curl versions curl-7.58 and newer need to add --location-trusted flag if you are including an Authorization header
So i am including an Authorization header
Requests does not handle 100 responses currently because the underlying Python libraries are unable to handle them. This is a known issue but until Python has support or we replace the library underpinning urllib3, we won't be able to provide support for this.
found here https://github.com/psf/requests/issues/5190
seems like not if you're using requests
What exactly is the issue
and generally, servers shouldn't be sending 100 status codes:
As the HTTP/1.0 standard did not define any 1xx status codes, servers must not send a 1xx response to an HTTP/1.0 compliant client except under experimental conditions.
Cuz im not 100% understanding it
what is the issue that is causing the requests library to not be able to handle the 100 status code? (is that your question?)
Cuz i've been having this issue since yesterday. wget is getting 200, curl only gets 200 if added --trusted thingy, System.Net.HttpWebRequest (microsoft) is getting 403 and pythong requests as well. Insomnia is getting 200, postman gets 403
While learning Django, I was taught to setup the HTML template like this so that the form would be re-directed to a view that had an if request.method == 'POST'...
<form method="POST" action="{% url "my_app:url_namespace" ARGUMENT %}">
--- snip ---```
However, my current book is ommiting the action= and it still works. The form/model is pretty much identical...
<form method="POST">
--- snip ---```
From what I could guess, by default the form gets submitted back to the same URL it came from if no action is specified. Is that right?
This class of status code indicates a provisional response, consisting only of the Status-Line and optional headers, and is terminated by an empty line. There are no required headers for this class of status code. Since HTTP/1.0 did not define any 1xx status codes, servers MUST NOT send a 1xx response to an HTTP/1.0 client except under experimental conditions.
Wait can u guys back it up for a second
then I'm not wrong lol
I'm not familiar with HTTP 1.0 and 1.1 thingies
what I said was exactly correct
You won't see it because the browser handles it
But i've used like 5 HTTP clients
none of them indicated anything like 100
only 302 -> 403 / 200
So the clients handle this as well?
ideally, yes, but it depends on the client
A http client will receive e.g. 304 all the time but never tell you
but this is horrible while debugging the issue
Cuz i'm getting inconsistent results per-client
yeah i've seen e-tags popping around here and there
but i dont even know what they do
It's in patch review
so maybe it finally drops with 3.9
What does the 100 continue flow do?
like a pre-request communication something?
The HTTP 100 Continue informational status response code indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished.
To have a server check the request's headers, a client must send Expect: 100-continue as a header in its initial request and receive a 100 Continue status code in response before sending the body.
why doesnt
headers = {
"Expect": "100-continue",
"authorization": f'LOW {access_key}:{secret_key}'
}
response = requests.request("GET", url, data=payload, headers=headers)
work then?
because the underlying libraries cannot handle it
they don't know what to do with 100
you'll need to use a different language
Ok that's fine, i was only using python to check if it works
I'm actually trying to do this on c#
i hope its client can handle this
fingers crossed
@native tide E-Tags are a hash of the content and you first send a http request without it, then the server responds with E-Tag: number and you are supposed to send it with the next request. If the content did not change, the server will send "an empty" package with 304 not modified as status code.
Otherwise 200 OK with the new content
but it does
or something is wrong with your authentication
Yeah i've been through that
Many times now
The auth works on wget / curl --trust / insomnia
so it's working
Also tried it without the auth header on those clients
it gets a 403
so the header is fine
try using the curl api?
For?
what you are doing
CURL has a programming interface via their library
C bindings
see if you can get it on nuget
oki
On stackoverflow they say not to call curl
options are basically:
Well, you wouldn't call cURL directly, rather, you'd use one of the following options:
HttpWebRequest/HttpWebResponse
WebClient
HttpClient (available from .NET 4.5 on)
I'd highly recommend using the HttpClient class, as it's engineered to be much better (from a usability standpoint) than the former two.
Webclient no luck
not sure if you've seen it but it looks like they have an API https://archive.org/services/docs/api/index.html
Yes im using the api
and a CLI which has a download command written in python https://github.com/jjjake/internetarchive/blob/master/internetarchive/cli/ia_download.py
A Python and Command-Line Interface to Archive.org - jjjake/internetarchive
Yeah i've used the cli
BTW wtf
How does their cli work?
They manage to get around the 100-continue
ive read through the cli library a few times
So apparently it is possible
I'm seriously losing my mind rn
I have to be missing something
missing something that causes some clients to get 200 and others 403
And so I'm not sure if it's caused by the expect 100-continue or not
try running it directly from the cli code and not using it as a cli and setting the log level to DEBUG
like i'm digging through exactly this part a lot: https://archive.org/services/docs/api/ias3.html
Yes how do i do that?
Cuz yesterday i was trying to use wireshark to check all outgoing http requests
how to check how their headers etc. looked in contrast to clients that are not working
U mean like clone the repo and then do: $ ./__init__.py ia download "....file.iso"
import logging
logging.getLogger().setLevel(logging.DEBUG)
...
# import from ia package and download a file
I was even talking like going into an interactive python repl and try doing it from there
considering what he is downloading, we should probably stop helping at this point
@cold anchor
nah hold on guys before all the piracy stuff
I'm trying to make a general IA downloader
Not for roms / isos
but these specifically had private files
that's why im doing the testing mostly on this
you're making a public downloader for private files?
Well you can access them if you have the correct credentials
So users can log in through the app
And then i can request their access / secrets through /login
but you're giving IA the same credentials no matter the user on your end?
and present them the files
no u can use their endpoints
to get access / secret
same thing the cli is using
I'm confused on the difference between what you're making and what IA already is/does
https://archive.org/services/xauthn/ with params: op=login then email + password
IA has a python cli client, but not an easy way for basic users to have the same funcionality
I'm still confused, are you logging in for users on their behalf to make it a better user experience?
And there's like 0 examples with open source projects
Yes, it's a very well made platform already, im just trying to develop on top of it to give basic users more options
Access to the Archiveβs Collections is provided at no cost to you and is granted for scholarship and research purposes only. The Archive, at its sole discretion, may provide you with a password to access certain Collections, provided that you complete any required application process and provide accurate information in your application. You may use your password only to access the Collections in ways consistent with this Agreement β no other access to or use of the Site, the Collections, or the Archive's services is authorized. You agree not to interfere with the work of other users or Archive personnel, servers, or resources. **Further, you agree not to recirculate your password to other people or organizations. **
I can't help with this any further, unfortunately
Ah ok, so I can't legally make an app since they would have to provide me with their credentials?
that's how I read it but I'm no lawyer and will err on the side of safety here
fair enough, thanks for the help anyways, since besides IA this authorization method is used by s3 aws as well
@proper hinge
If i add primary_key to
user_id=Column(Integer, ForeignKey(βusers.idβ))
Itll give a list of the usersβ id, am i right?
you mean if you do user_id=Column(Integer, ForeignKey(βusers.idβ), primary_key=True) ?
Yeah
that makes the column user_id on that table the primary key for that table
whatttt no module named sqlite3 but I downloaded python 3.8.3 from the source on ubuntu.... this is the error I get when doing python manage.py runserver do I really need to uninstall python -.-.-.-
posted in #databases as well:
I'm using mongodb (flask-mongoengine) with flask-login and flask-user for a web app and I'm wondering how or if I can do role based login with this setup:
from flask_mongoengine import MongoEngine
from flask_user import UserMixin
db = MongoEngine()
class User(db.Document, UserMixin):
# User authentication information
username = db.StringField(default='')
password = db.StringField()
roles = db.ListField(db.StringField(), default=[])
class Vendor(db.Document):
brand = db.StringField(default='')
location = db.PointField(auto_index=False)
max_occupants = db.NumberField()
current_occupants = db.NumberField()
user_queue = db.NumberField()
number_up = db.NumberField(),
meta = {
'indexes': [[("location", "2dsphere"), ("datetime", 1)]]
}
class Order(db.EmbeddedDocument):
id = db.ObjectIdField(required=True, default=db.ObjectId,
unique=True, primary_key=True)
vendor = db.ReferenceField(Vendor)
order_number = db.NumberField(required=True)
called_number = db.BooleanField()
class Customer(db.Document):
# User information
first_name = db.StringField(default='')
last_name = db.StringField(default='')
orders = db.ListField(db.EmbeddedDocumentField(Order))
just sharing
from string import Template
internal_page_temp = Template('<a href="$slug">$text</a>')
DISPLAY_PAGES = ['about', 'archive']
SIDEBAR_LINKS = [
internal_page_temp.safe_substitute(
slug=f"/{x.replace(' ', '-')}/",
text=x.title()
) for x in DISPLAY_PAGES
]
can you integrate a python script into a website as easily as a JS script?
I apologize if this isn't the right place to ask, but does anyone know how I could add a second line to a div with a different font size?
JS runs in the browser, python cannot. you'd have to run your python script on the server side of the website
if you want a div with two font sizes you should use 2 different divs
Hi is it possible to make a Firefox extension using python?
you can make a browser extension that talks to a python backend, but browser extensions must be written in javascript
Thanks @rdbaker
Let's say you have a registration page where users can register for your website. What exactly would you name the html file, the view, and the url? I imagine it doesn't really matter as long as it works, but would you just name them all register?
@native tide yeah, nothing is wrong with naming different parts of the app the same thing ... the important thing is to ensure you're cleanly and clearly naming what it is/does
and the view, route, and template file are all for registering after all, so it makes perfect sense to name them all register
@restive arrow there is brython, https://brython.info/
Brython
needed a help with django
my prevous entries in a model dont let me migrate a two new fields added tothe same model
i am not able to delete those entries too
Need help with Django
Mainly the problem is html /css
I can't layout this page
I tried the vertical lines but I can't seem to make all the lines connected
@everyoneHi
Hello, I love programming, and I would like to learn python
The little problem is that I speak French
@deep cave Hi
@sturdy sapphire ou code with sublimpe text cool! what language do you code?
So.....
!tempmute @still chasm 24h Do not try to ping @ everyone in a community with over 50,000 users. Do not ping random staff members. Don't introduce yourself in #web-development, that's what #python-discussion is for. I get that you're new here, but please try to use some common sense.
:incoming_envelope: :ok_hand: applied mute to @still chasm until 2020-05-20 09:26 (23 hours and 59 minutes).
@native tide thanks
Anyone know a good way to convert HTML to PDF?
just gonna nap this from a css chat im in:
Thanks @quick cargo π
theres also html2pdf
which is server side
so either would work iirc just depends on if u want it client or server sided
Well I'm using flask as the WSGI.
I do know some js, but I haven't been using it for a while. I have a bootstrap table I want to convert to PDF
I think I have found something amazing... Flask-WkHTMLtoPDF
You can use api's availble online if its not sesnitiove data
Any web developers who could help with figuring out how much to charge for a building a wewbsite?
guuys
why i get error post is undefined
@app.route('/posts/pinn/<int:id>')
def pinn(id):
post = BlogPost.query.get_or_404(id)
if request.method == 'POST':
post.pinn = request.form['pinn']
if post.pinn is True:
post.pinn = False
db.session.commit()
else:
post.pinn = True
db.session.commit()
else:
return render_template('posts.html', post=post)```
{% block head %}
<title>Posts</title>
{% endblock %}
{% block body %}
<h1>All Posts</h1>
<hr>
<h2>Create New Blog Post:</h2>
<form action='/posts' method='POST'>
Title: <input type='text' name='title' id='title'>
<br>
Author: <input type='text' name='author' id='author'>
<br>
Post: <input type='text' name='content' id='content'>
<br>
<input type='submit' value='Post'>
</form>
<hr>
<div class="pin">
{% for post in posts if post.pinn.True %}
<h2>{{ post.title }}</h2>
{% if post.author %}
<h3>By: {{ post.author }}</h3>
{% else %}
<h3>By: N/A</h3>
{% endif %}
<p>{{ post.content }}
</p>
<a href='/posts/delete/{{post.id}}'>Delete</a>
<a href='/posts/edit/{{post.id}}'>Edit</a>
<p id='time'>{{ post.date_posted }}</p>
<a id='open' href='/post/{{post.id}}'>Open post</a>
<a id='pinn' href='/posts/pinn/{{post.id}}'>Stick</a><hr>
</div>
{% else %}
<div class="unpin">
<h2>{{ post.title }}</h2>
{% if post.author %}
<h3>By: {{ post.author }}</h3>
{% else %}
<h3>By: N/A</h3>
{% endif %}
<p>{{ post.content }}
</p>
<a href='/posts/delete/{{post.id}}'>Delete</a>
<a href='/posts/edit/{{post.id}}'>Edit</a>
<p id='time'>{{ post.date_posted }}</p>
<a id='open' href='/post/{{post.id}}'>Open post</a>
<a id='pinn' href='/posts/pinn/{{post.id}}'>Stick</a><hr>
{% endfor %}
</div>
{% endblock %}````
Anyone know how with flask I can get a url for a file that isnβt in the static folder
can developer tools be disabled on a page through script ?
no
And it's a futile exercise to try and disable anything.
In fact, I'd see your site as malicious if you tried to do that @amber moat
i'm asking because it doesn't work on the bookmarks page
on vivaldi
i tried ctrl+shift+i
That is part of the program, not a webpage per se
it did work for firefox on a new private tab
@glossy halo - html <img src="/static/images/mypic.jpg">
Then open a bug report with Vivaldi
what i believe is that vivaldi is an electron app and uses html css
so the bookmarks page might also be a html page
Then take it up with the developers of Vivaldi. Nothing we can do about it
alright. i was feeling that the html pages might be protected when i tried opening them using a web server they didn't work and that is also not an extension
found this
and this too
this did it: --flag-switches-begin --debug-packed-apps --silent-debugger-extension-api --flag-switches-end
guys do you know maybe know what would be error in 'post' is not defined
or how to define it
flask
hey i read that django is a full stack webdev framework for python, would someone like to come over to a vc and talk a bit about it with me
i just started learning pyhton a little bit over 3 months and got the basics now, so i thought that i could start making my very first webpage
hi. I'm ok with the language itself, but unsure how to go about using it in a web page. Is there a good tutorial or example someone can recommend?
Hey if anyone needs help with django then let me know
@remote ruin or @final viper I could share link for a few good youtube tutorials
so what do you want help with?
I am quite familiar with django ..... recently built a web ui with complete backend integration and authentication feature
@calm pond i was more looking for a chat about it, becoz i heard from many ppl that they wouldnt recommend, but they are actually not pyhton-devs, so i dont know....a little chat about your opinion and experience would be amazing. my youtube to-watch-list is already endless π
a nooby (me) wants to talk with a (senior) and listen to his thoughts
I need to see the html
like the empty part between the words are also links
#nav-bar ul{
padding:0;
list-style:none;
text-align:center;
}
#nav-bar li{
display:inline;
position: fixed;
}
#nav-bar a{
color:#05386b;
text-decoration:none;
font-size: 21px;
padding-right:20px;
font-weight:600;
}
thats the css lol
oh shit my bad
you want to make the gap bewtween each nav-link larger?
<div class='container'>
<ul>
<li><a href='#'>Home</a></li>
<li><a href='#'>Useful Subreddits/Websites</a></li>
<li><a href='#'>About Me</a></li>
<li><a href='#'>Contact Me</a></li>
</ul>
</div>
</nav>```
i mean like
its giving me the "click on link" mouse cursor
on the empty part
i want that gone
make the link hitbox smaller
oh
is there any way i can spread them out
if i remove it they are too close to each other
oh wait nvm
yeah i was thinking that aswell
a lot of my web dev process is just trying shit out until i get a result i want lol
lmao
also 1 more question
do u know how i can make an element stay on the screen
even when i scroll
like for example the navigation bar
mmmm yes and no
I dont remember exactly how to do it but ive done it before. but i can help find it for you
id really appreciate it π
theyre called sticky elements
if you havent seen this site before, I really recommend it for any web shit. they teach you a lot of design structure concepts
like parallax scroll which is really cool
its a lot simpler than I thought lol. You just put a position: sticky; in the div you want to stick
thats nice
yeah
web development seems so much easier than python
just gotta remember some values
i probably have to learn django next π©
@distant trout yes bro. Go on. Django is easy