#web-development
2 messages ยท Page 19 of 1
nah?
atleast
if you use flask for example
you can add python functions to jinja
and execute them within your template
yep its everything
no other tags
just that specific one
also do you be ok with me using sqlite in development with a small website ๐
yeah why not ?
some other people get angwy
idc what you use ๐
mm
I mean, i use sqlite3 + sqlalchemy
im just going to use sqlite for small projects
so i can make relations
yeah me aswell
(learning it atm, bit stuck on relationships with it but trying again tomorrow)
they have it really nice documented
i like the simplicity of it but i know that sqlalchemy is better at more complicated things
~~on the django part ~~
I would choose flask over django just because you really install what you need and nothing else
yeah
can be tricky getting rolling kinda thing but once you have built a nice infastructure for everything, its nice to use
it really is
also my pc has 64gb disk space (cheap netbook that i hacked linux onto) so i dont really have space for django with small projects
maybe a idea to look into a docker container running a alpine postgress container if you are short on space
good replacement for sqlite3
i am making a cloud server
got the hard drive
got the server
only problem is locally-hosted cloud servers are way slower than something like dropbox for whatever reason
its weird
maybe configuration settings
whats the point of backref in sqlalchemy when dealing with relationships?
i understand all of the basics but just not what the backref is used for
class Puppy(db.Model):
__tablename__ = 'puppies'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
# one to many relationship. ([STRING: What your connecting], backref=[STRING: Name so the connected model can use???], lazy=[STRING: leave dynamic most of the time])
# Puppy --> Many Toys
toys = db.relationship('Toy', backref='puppy', lazy='dynamic')
# one to one
# Puppy --> One Owner
owner = db.relationship('Owner', backref='puppy', uselist=False) # leave lazy to default, dont use list but just 1 item
def __init__(self, name):
self.name = name
def __repr__(self):
if self.owner: # if puppy has owner
return f'<name: {self.name}, owner: {self.owner.name}>'
else:
return f'<name: {self.name}, no owner>'
def report_toys(self):
print('Here are my toys:')
for toy in self.toys:
print(toy.item_name)
class Toy(db.Model):
__tablename__ = 'toys'
id = db.Column(db.Integer, primary_key=True)
item_name = db.Column(db.Text)
# connect toys to puppies. puppies is Puppy's __tablename__ and we are getting the id of it
puppy_id = db.Column(db.Integer, db.ForeignKey('puppies.id'))
def __init__(self, item_name, puppy_id): # when you make this, it always has to have a name and puppy that owns it
self.item_name = item_name
self.puppy_id = puppy_id
class Owner(db.Model):
__tablename__ = 'owners'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
puppy_id = db.Column(db.Integer, db.ForeignKey('puppies.id')) # owner connected to puppy, as said above
def __init__(self, name, puppy_id):
self.name = name
self.puppy_id = puppy_id
nowhere is puppy used
@app.route('/login')
async def login():
DISCORD_OAUTH_URL = "https://discordapp.com/api/oauth2/authorize?client_id=538438973052289084&redirect_uri=http%3A%2F%2F127.0.0.1%3A5000%2Flogin&response_type=code&scope=email%20identify%20guilds%20guilds.join"
CODE = request.args.get("code")
if not CODE:
return quart.redirect(DISCORD_OAUTH_URL)
else:
payload = {
"client_secret": "censored",
"client_id": bot.user.id,
"grant_type": "authorization_code",
"code": CODE,
"redirect_uri": "http://127.0.0.1:5000/login",
"scope": "guilds%20guilds.join%20identify%20email"
}
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
async with bot.session.post(f"{API_ENDPOINT}/oauth2/token", headers=headers, json=payload) as resp:
resp = await resp.json()
This is the code
and this is the error: RuntimeError: Timeout context manager should be used inside a task
@brave mantle
That's not enough of a traceback
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 1462, in handle_request
return await self.full_dispatch_request(request_context)
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 1484, in full_dispatch_request
result = await self.handle_user_exception(error)
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 911, in handle_user_exception
raise error
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 1482, in full_dispatch_request
result = await self.dispatch_request(request_context)
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 1530, in dispatch_request
return await handler(**request_.view_args)
File "C:/Users/HP/PycharmProjects/quarttest/test.py", line 63, in login
async with bot.session.post(f"{API_ENDPOINT}/oauth2/token", headers=headers, json=payload) as resp:
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\aiohttp\client.py", line 855, in __aenter__
self._resp = await self._coro
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\aiohttp\client.py", line 321, in _request
with timer:
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\aiohttp\helpers.py", line 658, in __enter__
raise RuntimeError('Timeout context manager should be used '
RuntimeError: Timeout context manager should be used inside a task
Full traceback
@brave mantle
Where did you create your aiohttp session?
In my bots subclass
OK, where?
class Bot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.dashboard = Dashboard()
self.session = aiohttp.ClientSession(loop=self.loop)
that'll be it
They're supposed to be created within a coroutine
you could use the on_ready event
if quart.request.method == "POST":
nick = (await quart.request.form)["nick"]
guild = bot.get_guild(id)
__bot_user = guild.get_member(bot.user.id)
await __bot_user.edit(nick=nick)
return "Changed nick!"
Error:
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 1462, in handle_request
return await self.full_dispatch_request(request_context)
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 1484, in full_dispatch_request
result = await self.handle_user_exception(error)
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 911, in handle_user_exception
raise error
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 1482, in full_dispatch_request
result = await self.dispatch_request(request_context)
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 1530, in dispatch_request
return await handler(**request_.view_args)
File "C:/Users/HP/PycharmProjects/quarttest/test.py", line 121, in dashboard
await __bot_user.edit(nick=nick)
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\member.py", line 479, in edit
await http.change_my_nickname(guild_id, nick, reason=reason)
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\http.py", line 154, in request
async with self._session.request(method, url, **kwargs) as r:
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\aiohttp\client.py", line 855, in __aenter__
self._resp = await self._coro
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\aiohttp\client.py", line 321, in _request
with timer:
File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\aiohttp\helpers.py", line 658, in __enter__
raise RuntimeError('Timeout context manager should be used '
RuntimeError: Timeout context manager should be used inside a task
@brave mantle
I think it's because of await __bot_user.edit(nick=nick)
is there any normal first "public" website that people make?
im going to make a server list, similar to a blog but edited for servers (as in users post game servers and people can like them, like you can do with blogs)
(Django ) I'm trying to get my form to display a quiz with its questions - and it does with a GET request. But creating a form instance with POST request doesn't work - request.POST contains dict with strings (answers to questions) while my form's init expects a questions argument.
class QuizPageForm(forms.Form):
def __init__(self, questions, *args, **kwargs):
super(QuizPageForm, self).__init__(*args, **kwargs)
for counter, question in enumerate(questions):
choice_list = []
for choice in (question.get_choices()):
choice_list.append((choice.pk, choice.choice_text))
self.fields["question{}".format(counter)] = forms.ChoiceField(label=question.get_question_text(),
choices=choice_list,
widget=forms.RadioSelect)
Can anyone help me find material static UI templates for a web app related to Disaster Response. The web app will be using Google Maps API.
Hello Guys, How can I serve CSS and JS files on an Aiohttp web app?
can any one help me in the project structure of flask api
@spring mist Please see #help-croissant
@coral ridge and @native tide - Having some problems with this now. Any thoughts?
function copyMessage() {
var copyText = document.getElementById("encryptedMessage");
var copyBttn = document.getElementById("copyText");
if (copyBttn.click()) {
copyText.select();
document.execCommand("copy");
alert("Copied your encrypted message to the clipboard!");
}
}
{% extends 'layout.html' %}
{% from 'bootstrap/form.html' import render_field %}
{% block body %}
<br />
<div class="alert alert-success" role="alert">
<h2 style="text-transform: uppercase; font-weight: bold; text-align: center;">Your Original Message:</h2>
<p style="text-align: center;">{{ user_message }}</p>
</div>
<br />
<div class="alert alert-secondary" role="alert">
<h2 style="text-transform: uppercase; font-weight: bold; text-align: center;">Your Encrypted Message:</h2>
<p id="encryptedMessage" style="text-align: center;">{{ output }}</p>
</div>
<br />
<div class="alert alert-danger" role="alert">
<h2 style="text-transform: uppercase; font-weight: bold; text-align: center;">Your Secret Key:</h2>
<p style="text-align: center;">{{ secret_key }}</p>
</div>
<br />
<button type="button" onclick="copyMessage()" id="copyText" class="btn btn-primary btn-lg btn-block">Copy message to clipboard</button>
<br />
{% with messages = get_flashed_messages() %}
{% if messages %}
<div class="alert alert-success" role="alert">
{{ messages }}
</div>
{% endif %}
{% endwith %}
{% endblock %}
Or if anyone else has any thoughts would be greatly appreciated. Thanks in advance.
the flashed messages is not displaying correctly right?
No sorry it's not running the JS correctly as in it's not copying the test and displaying the confirmation alert.
I think it's because you called .click() as a method and it returns undefined
So I would need to attach a function to it? For example...
you want the code to invoke on click right?
Yes please.
you have to hook to the click event with copyBttn.addEventListener
copyBttn.addEventListener('click');
if (copyBttn.click()) {
copyText.select();
document.execCommand("copy");
alert("Copied your encrypted message to the clipboard!");
}
put the 2nd argument of .addEventListener as the function to invoke when it's clicked
if (copyBttn.click(), copyBttn.addEventListener) {
copyText.select();
document.execCommand("copy");
alert("Copied your encrypted message to the clipboard!");
}
Sorry.
if (copyBttn.click(copyBttn.addEventListener) {
copyText.select();
document.execCommand("copy");
alert("Copied your encrypted message to the clipboard!");
}
like
copyBttn.addEventListener("click", function(event) {
// the rest here
})
if (copyBttn.addEventListener("click", copyMessage())) {
copyText.select();
document.execCommand("copy");
alert("Copied your encrypted message to the clipboard!");
}
copyBttn.addEventListener("click", function(event) {
copyText.select();
document.execCommand("copy");
alert("Copied your encrypted message to the clipboard!");
})```
Yeah sorry I was just reading up on it and noticed that is the correct way of doing it. Apologies. I will try this.
It's not accepting the request so I think it may be a problem with linking the static file.
No it's still not working.
@primal sinew What is not working?
It would appear the whole entire script at this point. Here is the JS code.
function copyMessage() {
var copyText = document.getElementById("encryptedMessage").innerHTML;
copyText.select();
document.execCommand("copy");
alert("Copied your encrypted message to the clipboard!");
}
document.getElementById("copyText").addEventListener("click", copyMessage);
Here is my template...
{% extends 'layout.html' %}
{% from 'bootstrap/form.html' import render_field %}
{% block body %}
<br />
<div class="alert alert-success" role="alert">
<h2 style="text-transform: uppercase; font-weight: bold; text-align: center;">Your Original Message:</h2>
<p style="text-align: center;">{{ user_message }}</p>
</div>
<br />
<div class="alert alert-secondary" role="alert">
<h2 style="text-transform: uppercase; font-weight: bold; text-align: center;">Your Encrypted Message:</h2>
<p id="encryptedMessage" style="text-align: center;">{{ output }}</p>
</div>
<br />
<div class="alert alert-danger" role="alert">
<h2 style="text-transform: uppercase; font-weight: bold; text-align: center;">Your Secret Key:</h2>
<p style="text-align: center;">{{ secret_key }}</p>
</div>
<br />
<button type="button" id="copyText" class="btn btn-primary btn-lg btn-block">Copy message to clipboard!</button>
<br />
{% with messages = get_flashed_messages() %}
{% if messages %}
<div class="alert alert-success" role="alert">
{{ messages }}
</div>
{% endif %}
{% endwith %}
{% endblock %}
Where are you including the script?
I have tried in the main layout template file as well as the one above using url_for()
<script type="text/javascript" src="{{ url_for('static', filename='main.js') }}"></script>
Yes that is what I have included but still no joy.
Even the text/javascript part? Leaving it out will cause the script to not work
No even that as well.
Is there any faults with the JS code at all that's all I can think of?
I'm not a JS expert but you don't need document.getElementById("copyText").addEventListener("click", copyMessage);
You can just do
<button type="button" id="copyText" class="btn btn-primary btn-lg btn-block" onclick="copyMessage()">Copy message to clipboard!</button>
Also you can try if the function works by opening the dev console and calling the function there
OK leave with me and I will have another play. Really appreciate you taking the time to help though.
Yeah there are errors with the JS code. Thanks for the suggestion of the dev tools. This will help.
@primal sinew I think the thing is that it has to be an input field you are copying from
Yeah I have just thought of that. I will try this and give it a go. Leave with me.
Nope same thing. Still getting error of copyText.select is not a function
It looks as if there is an issue with javascript copyText.select();
Sorted it @coral ridge and @hallow raft . Was including an additional innerHTML tag that wasn't required. Thanks for your help.
Cool! ๐
Is anyone here able to answer a socket handshake related question?
TCP/IP protocol
i got {% if g.user %} <p style="display:inline">Welcome back!</p> {% if not g.user.membership %} <a href=" {{ url_for('apply') }}">Apply.</a> {% endif %} <a href=" {{ url_for('profile') }}">Profile.</a> <a href=" {{ url_for('logout') }}">Logout.</a> {% else %} <p style="display:inline">You are not logged in.</p> <a href=" {{ url_for('login') }}">Login.</a> {% endif %} and I'm getting 'NoneType' object has no attribute 'membership' but it should never get to that point if g is NoneType. i assume im wrongly nesting if statements?
anybody know how to setup leaflet plugins in django by using django-leaflet or any other way ? I want to add leaflet-sidebar plugins.
@polar robin not sure if you solved your issue, but in Jinja you need to use the builtin test none: if g.user is not none
Hi everyone, I'm one of the Flask maintainers! We're running our first every Community Survey, it would be greate to hear from you: https://twitter.com/davidism/status/1090364867905609728
Take the Flask/Pallets Community Survey! ๐๐
https://t.co/fSW0Qr7HuF
Knowing more about our community and your projects will help us decide what to focus on for Flask and the other Pallets projects. Please share the link!
hey, im trying to make to backend todo app in django rest framework and i want to know how can you move a json object into another model when there is a get request on a certain url. Please help
I have made the api to return a list of all the tasks and to add new tasks. Now i need help with how to move the tasks into another table of "Completed tasks"
no one?
Nobody's answered you because the correct answer is "that's not what you want"
You should have a single table for tasks and have a completed column
SQL databases are designed to work across large tables with lots of rows
rather than a bunch of smaller tables
In order to keep things optimised, you should avoid "moving" rows between tables
(realistically, that move is not a move, it's a deletion of the row in the first table and an insertion into the other one)
okay thanks...ill work on that! ๐ธ
ITS WORKING!! ๐
All of a sudden my app is not display bootstrap correctly from it's module when I include html {% from 'bootstrap/form.html' import render_field %} in my template. Any idea what could cause this? I have since worked on my scripts today but as of this morning everything was working correctly.
Never mind, sorted it thanks.
I am trying to decrypt an existing encrypted message. Basically the user will paste the encrypted message and private key into a form and it would show the decrypted output. Here is the code.
@app.route('/decrypted')
def decrypted():
# Registering forms
decrypt_form = DecryptMessage(request.form)
decrypt_form.validate_on_submit()
# Pulling data from form
m = decrypt_form.message_field.data
k = decrypt_form.key_field.data
# Converting private key to bytes
k_bytes = k.encode(encoding='UTF-8')
# Generate new key
base64_key = base64.b64encode(bytes.decode(k_bytes))
g = Fernet(base64_key)
# Decrypt message
decrypt_message = g.decrypt(m)
final_output = decrypt_message
return render_template('decrypted.html', final_output=final_output)
I get an error in debug mode stating TypeError: a bytes-like object is required, not 'str'
I assume this is something to do with assigning a new key?
Any suggestions would be greatly appreciated. Many thanks in advance.
which line is the error?
I think it maybe the line python base64_key = base64.b64encode(bytes.decode(k_bytes))
Screenshot.
U dont need to use python bytes.decode(k_bytes)U use it like: python k_bytes.decode()the decode() function takes an argument encoding= but the default is UTF-8 so u dont need to pass that arguement
I thinks this should work @primal sinew
@alpine socket Amended code ```python
@app.route('/decrypted')
def decrypted():
# Registering forms
decrypt_form = DecryptMessage(request.form)
decrypt_form.validate_on_submit()
# Pulling data from form
m = decrypt_form.message_field.data
k = decrypt_form.key_field.data
# Converting private key to bytes
k_bytes = k.encode()
# Generate new key
base64_key = base64.urlsafe_b64encode(k_bytes.decode())
g = Fernet(base64_key)
# Decrypt message
decrypt_message = g.decrypt(m)
final_output = decrypt_message
return render_template('decrypted.html', final_output=final_output)
yes ๐
@alpine socket Sadly not. Still getting the same error. ๐ฆ
the urlsafe_b64encode() takes a bytes like object hence you do not need to decode the variablek_bytes
@primal sinew
@alpine socket ```python
@app.route('/decrypted')
def decrypted():
# Registering forms
decrypt_form = DecryptMessage(request.form)
decrypt_form.validate_on_submit()
# Pulling data from form
m = decrypt_form.message_field.data
k = decrypt_form.key_field.data
# Converting private key to bytes
k_bytes = k.encode()
# Generate new key
base64_key = base64.urlsafe_b64encode(k_bytes)
g = Fernet(base64_key)
# Decrypt message
decrypt_message = g.decrypt(m)
final_output = decrypt_message
return render_template('decrypted.html', final_output=final_output)
yes...hopefully ๐ค
Now I am getting error message ValueError: Fernet key must be 32 url-safe base64-encoded bytes.
@alpine socket No sorry. Still not working. I have even tried ```python
base64_key = base64.urlsafe_b64encode(k_bytes[:32])
I appreciate your help by the way. ๐
base64.urlsafe_b64encode() should work...but i dunno
no problem ๐ธ
the value eroor is at which line?
Line 37 which is this ```python
base64_key = base64.urlsafe_b64encode(k_bytes)
I have just tried this in all in IDLE and it looks OK to me. ๐ฆ
OK I am progressing with this now. Here is the updated code: ```python
@app.route('/decrypted')
def decrypted():
# Registering forms
decrypt_form = DecryptMessage(request.form)
decrypt_form.validate_on_submit()
# Pulling data from form
m = decrypt_form.message_field.data.encode()
k = decrypt_form.key_field.data
# Converting private key to bytes
k_bytes = k.encode()
# Generate new key
base64_key = base64.urlsafe_b64encode(k_bytes [:32])
g = Fernet(base64_key)
# Decrypt message
decrypt_message = g.decrypt(m.decode())
final_output = decrypt_message
return render_template('decrypted.html', final_output=final_output)
I think the problem now is passing an already encrypted message to the decrypt function as I now get the error message: TypeError: token must be bytes.
So I have since managed to pass the encryption key as bytes using the following code: ```python
@app.route('/decrypted')
def decrypted():
# Registering forms
decrypt_form = DecryptMessage(request.form)
decrypt_form.validate_on_submit()
# Pulling data from form
m = decrypt_form.message_field.data
k = decrypt_form.key_field.data
# Converting private key to bytes
k_bytes = k.encode()
# Generate new key
base64_key = base64.urlsafe_b64encode(k_bytes [:32])
g = Fernet(base64_key.decode(k))
# Decrypt message
decrypt_message = g.decrypt(m)
final_output = bytes.decode(decrypt_message)
return render_template('decrypted.html', final_output=final_output)
But I now get the error message: LookupError: unknown encoding: XQ5wNimxc3YdO3set1cpbjZq1AT3waC9m1wGV05wB3Y=
final_output = decrypt_message.decode()
and enter the encoding as a argument encoding="...'
@alpine socket Amended code: ```python
@app.route('/decrypted')
def decrypted():
# Registering forms
decrypt_form = DecryptMessage(request.form)
decrypt_form.validate_on_submit()
# Pulling data from form
m = decrypt_form.message_field.data
k = decrypt_form.key_field.data
# Converting private key to bytes
k_bytes = k.encode()
# Generate new key
base64_key = base64.urlsafe_b64encode(k_bytes [:32])
g = Fernet(base64_key.decode(k))
# Decrypt message
decrypt_message = g.decrypt(m)
final_output = decrypt_message.decode(encoding='ASCII')
return render_template('decrypted.html', final_output=final_output)
working? @primal sinew
Nope still the same error message sorry @alpine socket
Do I need to specify the encryption method?
i think the error might be in the line
g = Fernet(base64_key.decode(k))
Yes I think you're right.
because i think the decode func does not any arguments
Removed the argument and now have TypeError: argument should be a bytes-like object or ASCII string, not 'builtin_function_or_method'
It's a generated key that has been converted to a string. Basically I want someone to encrypt a message and send on details and be able to decrypt.
So the user would input the encrypted message and the private key and it would output the message in plain text.
If that makes sense! 
Goood morning awesome people, I am looking for some direction to improve the performance of this chunk of code.
if(ats_unts != "0"):
q = q.filter(unit_id=ats_unts)
if (res_status == "1"):
q = q.filter(ResultsID="PASSED")
if (res_status == "2"):
q = q.filter(ResultsID="FAILED")
q = q.filter(fixed_start_date__gte=start_date)
q = q.filter(fixed_start_date__lte=end_date)
q = q.filter(fixed_start_time__gte=start_time)
q = q.filter(fixed_start_time__lte=end_time)
q = q.order_by('-StartTime')[:1000]```
Currently this takes forever to run, is there a better way to handle user filtering? Python 3.7, Django 2.1.1
Just need to be pointed in the right direction. ๐ Thanks!
does django automatically combine filters like that?
you might be running a lot of nested subqueries, which your db engine might or might not be able to optimize
however you need to say:
- what database engine
- what part is slow (the db query, or something else)
- how big is the table
- how big is the result set
- do you have any indices on the table
- what is the cardinality of said indices
- what is your definition of "slow"
@outer marsh
Sorry to but in but is there any way to make <pre></pre> mobile responsive? My page just hides it being overflown on the x axis.
what do you mean hides?
<code>
i think should fix it
instead of <pre>
ah wait dont use code outside pre
hang on
yea that breaks the spaces
problem with code right
and you cant scroll that horizontally?
is I have a css that gives it a coloured background
i think you just dont get a scroll bar on mobile (i dont on iOS)
so it is in lines
you should still be able to scroll that horizontally
I skipped that via a div with a class
<div class="codeblock">
<pre>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Profile</title>
</head>
<body>
<p>Hello this is my profile page!</p>
</body>
</html></pre>
</div>
.codeblock {
background-color: rgba(45, 202, 255, .2);
border-radius: 0.25rem;
margin: 1em 0 1em 0;
padding: 1em;
}
shall I add that to the div since I want the rest of my content to fit onto the page
that doesn't work
so its working on mobile view which is nice to know
but stops at 374px
in browser
Sorted!
@surreal thicket I have kind of shifted gears since i asked this question earlier. The table in question is 41k rows, and im using sqlite. I have been preparing to migrate to MySQL - so now i am looking at a way to move the data .
that is harder. personally, i would load the sqlite data into pandas and write into mysql
41k rows is not that big
stellar that gives me a direction! thank you!
This wont probably fix my filtering issue - but the migration needs to happen so better now than later.
honestly that data set is small enough you can just load it in memory and do filtering in pandas ๐
hey
anyone here know django
my problem is that im trying to run "python manage.py migrate" but im getting this error "django.db.utils.IntegrityError: NOT NULL constraint failed: polls_comment.user_id"
Did you run makemigrations for your app?
hey, also a django question. how can I make an app 'global', so I can add it to INSTALLED_APPS without explicitly having the app in my project directory?
Hello,
I am building an rest app with flask using connexion and swagger.
I needed a custom sql wrapper for postgres so I tried attempting a extension for that based on example code on flask ext dev, but the passing app to init_app() results in not initializing the app.
Has anyone attempted anything like this?
Morning people. Still having issues with this. I have tested this in a python terminal and everything works OK so not sure if I am missing something? Here is the code: ```python
@app.route('/decrypted')
def decrypted():
# Registering forms
decrypt_form = DecryptMessage(request.form)
decrypt_form.validate_on_submit()
# Pulling data from form
m = decrypt_form.message_field.data
k = decrypt_form.key_field.data
# Converting data to bytes
m_bytes = m.encode(encoding='utf-8')
k_bytes = k.encode(encoding='utf-8')
# Generate new key
base64_key = base64.urlsafe_b64encode(k_bytes [:32])
g = Fernet(base64_key)
# Decrypt message
decrypt_message = g.decrypt(m_bytes)
final_output = decrypt_message.decode()
return render_template('decrypted.html', final_output=final_output)
I get the following error message cryptography.fernet.InvalidToken
Anyone?
No I have been trying the majority of last night and this morning. Looked through countless Stack and Reddit posts and still no joy.
I do believe I have tried removing the 32 previously and still had the same issue.
Removing that part of the code produces this error. ValueError: Fernet key must be 32 url-safe base64-encoded bytes.
There is obviously an issue turning the key from string format into bytes so that it can be used to decrypt the message.
@eager sorrel I would be more inclined to ask web scraping questions in one of the generic help channels, but... what's the question?
Ah I already asked In the help channels, thanks though
Hey all, apparently my google is failing me. In Django, if I want to .get an object where a m2m contains all elements exactly, how does that work?
MyModel.objects.get(some_m2m=?)
Is it a list of ids? List of objects? It keeps saying like it should be a an int or something
Full context
class Team(models.Model):
name = models.CharField(default='Random Team', max_length=300)
team_avatar = models.URLField()
players = models.ManyToManyField('Player', unique=True)
class Roster(models.Model):
match = models.ForeignKey('Match', on_delete=models.CASCADE, related_name='rosters')
player = models.ForeignKey('Player', on_delete=models.CASCADE, related_name='rosters')
team_number = models.IntegerField(blank=True, null=True)
slot_number = models.IntegerField(blank=True, null=True)
class Meta:
unique_together = ('match', 'team_number', 'slot_number')
def __str__(self):
return f"{self.player.display_name}: Team: {self.team_number} Slot: {self.slot_number}"
class Match(models.Model):
created = models.DateTimeField(auto_created=True, auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(choices=STATUS_CHOICES, max_length=300, default='in progress')
players = models.ManyToManyField(Player, through='Roster', related_name='matches')
def __str__(self):
return f"Match on {self.created}"
def get_team(self, team_number: int) -> Optional[Team]:
# How best to do this? Code throws error.
player_ids = [r.player.id for r in Roster.objects.filter(team_number=team_number)]
return Team.objects.get(players=player_ids)
Thoughts behind the setup to have Match have players as m2m be so I can associate teams and slot position of player. Really in perfect world would just be a m2m on Team but I don't know how I would record slot_ids per match unless I make that its own m2m.... which I guess is possible?
ive been trying to get a page to redirect a user when he registers an acc in the site
here is the function in views.py
can someone help please, its not redirecting
how hard is it to implament basic encryption into flask + sqalchemy?
just save password as a hash and hash users attemted password and see if it matches
with the salting things
okay so I'm an idiot
basically I'm using a module called Quart
which is esentially just asynchronous Flask
and am trying to put subdomains in
but it won't work
bp = Blueprint("main", __name__,subdomain="main")
that's how the blueprint is initialized
127.0.1.1 main.suhails-vps.localdomain suhails-vps
and that's my hosts file (I read online somewhere that I had to change it)
However I get this error:
run()
File "/var/www/new-spyke/assets/py/__init__.py", line 14, in run
load_blueprints(app)
File "/var/www/new-spyke/assets/py/__init__.py", line 25, in load_blueprints
app.register_blueprint(blueprint)
File "/root/.pyenv/versions/3.6.5/lib/python3.6/site-packages/quart/app.py", line 1169, in register_blueprint
blueprint.register(self, first_registration, url_prefix=url_prefix)
File "/root/.pyenv/versions/3.6.5/lib/python3.6/site-packages/quart/blueprints.py", line 678, in register
func(state)
File "/root/.pyenv/versions/3.6.5/lib/python3.6/site-packages/quart/blueprints.py", line 120, in <lambda>
strict_slashes=strict_slashes,
File "/root/.pyenv/versions/3.6.5/lib/python3.6/site-packages/quart/blueprints.py", line 742, in add_url_rule
strict_slashes=strict_slashes,
File "/root/.pyenv/versions/3.6.5/lib/python3.6/site-packages/quart/app.py", line 454, in add_url_rule
raise RuntimeError('Cannot use host or subdomain without host matching enabled.')
RuntimeError: Cannot use host or subdomain without host matching enabled.
if someone can @ me
Anyone?
@kindred gate I dont use blueprints, but I do use flask at work every day.
When you use blueprints, do you initialize a flask/quart app above the blueprint?
like if I wanted to enable host matching, instead of app = Flask(__name__) id have to do app = Flask(__name__, host_matching=True)
watcha got?
run()
File "/var/www/new-spyke/assets/py/__init__.py", line 13, in run
host_matching=True)
File "/root/.pyenv/versions/3.6.5/lib/python3.6/site-packages/quart/app.py", line 182, in __init__
'static_host must be set if there is a static folder and host_matching is '
ValueError: static_host must be set if there is a static folder and host_matching is enabled
i assume static_host is another kwarg that i need when initing the app
but what should it be?
@midnight kernel
hmm
what do you use in your static folder?
i use flask to build REST apis so the templates and static folder i have little experience in
i have JavaScript files, CSS files and images
or at least whatever is hosting the static folder
@midnight kernel I tried and now everything gives me 404 errrors
its probably being directed to the wrong place
i don't know how to change it though
everything worked fine before the subdomain change
So my django backend successfully manage to handle 170k+ real time users, I almost can't believe django can handle it.
that's awesome @sinful pulsar . I'm jut learning Django, great to see that it scales so effectively
@cerulean mauve good luck!
One of the biggest thing to consider when deploying django app is to make sure to choose your Gunicorn workers design wisely. Because it will also affect how you handle db connections.
It doesn't give me any problem until I start receiving 30k+ real time users
I am still learning about this though
My current objective is to create a functioning page, so the challenges that will come with scaling are a bit further down the line! ha ha. But it's definetly good to know. I'm excited about the possibilities I'm seeing opening up as I learn.
Hey, I got a responsive d3 graph that uses element.clientWidthand element.clientHeight for resizing. However, the clientHeightreturns 0 unless I have this CSS in place:
.graph {
position: absolute;
left: 0px;
right: 0px;
top: 0px;
bottom: 0px;
margin: 0px;
}
This works fine but if I want to add something else to the page, like a dropdown menu, it overlaps with the graph due to that CSS
Any ideas for a fix?
https://codepen.io/anon/pen/jdwPra here is a codepen that shows the issue better
What should i use to make a dynamic website, only python would be enough?
PHP?
and what sort of database should i use as well
i'm kinda new into web development stuff, will be helpful if you guys could link me to something where i could learn everything about this area.
@native tide might be best to ask in the #python-discussion channel
[Flask-Restful & Flask-sqlalhemy]: Umm, how do execute an database update? The documentation only has information how to do select, insert and delete.
Hi guys still looking for some advice on setting up django models
I've written up some history
Im trying to add commenting to my site in django. Right now I:'m getting this error "type object 'Poll' has no attribute 'get_absolute_url'"
any ideas on how to fix it
can you link to the docs? or reference where you've seen get_absolute_url used
i was looking at this indivdual video
In this video lecture, we will create a comment section specifically for post detail view. So, that the user/site vistor can comment to a particular post. Fi...
it talks about get abosolute url near the end
there it is a Post rather than a Poll
yea it is something you have to define, probably skipped in that vid or in a previous one
https://docs.djangoproject.com/en/2.1/ref/models/instances/#get-absolute-url
@fast narwhal
hey guys, trying to get rid of a n+1 problem... I know its select_related or prefetch_related but I guess I can't visualize it. Plugging in random ones with no affect (or even increasing query size).
Code:
Evaluating like [t.num_wins() fro Team.objects.all()]
Where would you guys recommend to start learning HTML and CSS? I want to start learning basic web development.
Some friends of mine have had some success with htmldog
i started with freecodecamp
Oh howwould I create my own webhook listener server
I'm using python Flask that is listening on port for POST requests
And I'm exposing that port to web by using ngrok
I'm pretty sure this isn't the best way
how to make wtforms actully pass to flask
its just appending at end of url for some reason
even with <form method="POST"></form>
Anyone who can help with viewing flask from an external ip / different host than localhost?
have tried app.run(host='0.0.0.0', port=3000)
@burnt silo same prob, hope we figure it out
That should work
Might need to do some port forwarding
But you should be able to access it inside your local network
Something to keep in mind is to include the port :D I've made that mistake too many times trying to access 192.168.0.1 without :5000 at the end
Hi, i want to ask something.
Im trying to deploy flask app to ubuntu server. I connected with ssh and following tutorial for deploy. There is apache on server and already running with 80 port for another php project. Tutorial steps telling me that create apache conf as follows.
ServerName yourdomain.com
ServerAdmin admin@yourdomain.com
WSGIScriptAlias / /var/www/Flask/flaskapp.wsgi
<Directory /var/www/Flask/Flask/>
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/Flask/Flask/static
<Directory /var/www/Flask/Flask/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>```
if im creating file like this, will it not be problem for the project already running on apache?
Umm, how would I get this to work?
from flask import request
from flask_restful import Resource
from models import db, Discord_Users
class UsersResource(Resource):
def get(self):
value = request.args.get('user_id')
if value is not None:
query = db.session.query(Discord_Users.user_id, Discord_Users.permission_granted) \
.filter(Discord_Users.user_id == value) \
.one()
return {'status': 'success', 'data': query}, 200
else:
return {'status': 'failed', 'message': 'This is not how it works'}, 400
Can someone help me out?
Instead of from flask_restful import Resource do from flask_restful import Resource, Api
Right under the import statements do app = Flask(__name__)
api = Api(app)
Under the class add api.add_resource(UsersResource, '/') if __name__ == '__main__': app.run(debug=True)
Does anyone run into problem with django imports?
@unkempt wharf No, as I have this.
Filename is app.py:
from flask import Blueprint
from flask_restful import Api
from resources.Hello import Hello
from resources.Messages import MessageResource
from resources.Messages import CountMessages
from resources.Messages import CountMessagesByChannel
from resources.Profiles import ProfilesResource
from resources.Users import UsersResource
api_bp = Blueprint('api', __name__)
api = Api(api_bp)
# Routes
api.add_resource(Hello, '/Hello')
api.add_resource(MessageResource, '/Messages')
api.add_resource(ProfilesResource, '/Profiles')
api.add_resource(CountMessages, '/UserMessageCount')
api.add_resource(CountMessagesByChannel, '/UserMessageCountByChannels')
api.add_resource(UsersResource, '/Users')
Also there is already a traceback, which says: TypeError: Object of type datetime is not JSON serializable.
So how do I serialize it?
Hey guys!
I want to host a mini-webshop on my poor Raspberry Pi. It's not supposed to have huge traffic, just some people in a group. I want to store the addresses with Flask, and use the PayPal checkout payment thing.
Is this dangerous?
@app.route("/interphore/early/code_here")
def interphore_early():
return app.send_static_file(
"/games/latest/interphore/early/code_here/interphore_early_play.html"
)
This is getting annoying
it clearly exists but it says it doesn't
What's ur entire code?
big
Could be due to the fact that you haven't restarted the python file?
It restarts when I save it.
Do all other parts of your site work?
Yup
specifically these two don't work
@app.route("/interphore/dev/code_here")
def interphore_dev():
return app.send_static_file(
"/games/latest/interphore/dev/code_here/interphore_dev_play.html"
)
@app.route("/interphore/early/code_here")
def interphore_early():
return app.send_static_file(
"/games/latest/interphore/early/code_here/interphore_early_play.html"
)
And if it's down to send_static_file, then I don't know how
Are those your only two routes with send_static_file
Maybe test it to return "hi" and see if the routing's the issue?
How do I load a new page on Flask
Without changing the url
Or, do I need to do that lol
New page?
@kindred gate
So it's your static file
Is the file in your static folder?
So the file is in static/games/latest...?
The only thing I can think of is that it can't find the file
In which case jinja would cause an exception
:/
did you add https::/ or whatever it is to the front?
It's localhost that's unlikely
The only thing I can think of is that the file directory is wrong
sorry
If you added the file after the code started running that could cause a problem
You might wanna restart the python file and see if that does anything
The app does but I don't think it grabs any new static files
I'm sorry I have no idea
The only thing I can say is double check to ensure your directory is right
Which it is
download might be corrupted
i had to delete all my d.py files and reinstall it before it started working right
(Intentionally censoring some of the code)
Also it works for everything else
Just the one fucking time i need to send_static_file
it fucking breaks
All other static files work, right?
Yes
Ant they all template
These ones
I cannot template
Which is why I am working with them differently
If there is any other way of loading static html from /static
I'd love to hear it
because this shit doesn't fucking work
flask.send_from_directory exists
yo ignore me if u want but i think you might be getting kind of heated, you should try taking a break to collect yourself so you can focus on it later.
Try your full directory
At least it gave a fucking readable error this time
not that it's anything good
I just forgot /static
...
I fucking copied the url
exactly
and it pulls this shit
C:\Users\Paws\Desktop\paraphore
so yes
it very much is
Never mind, the person I was making this for decided to fucking call it off
oof
I'm fucking done.
Hey at school there was recently a subject you could choose called Information technology i decided to choose the subject and right now we are learning html and css
im kinda ahead of the group and i was wondering what cool stuff i could do on the website
i have the background as a gif, ive learned to play mp4 files and videos, ive got headings, subheads and dot points
ive also done links and images
Look into javascript.
@hollow flower can i ask, what can i do with javascript on my website, the teacher said we will be learning that later, but i am down to get a headstart
To be quite honest, a lot of things. The loading on my website for example is done with javascript. (https://samip.fi)
and what about when i click the button and it scrolls down
That's CSS transition.
No problem. The HTML & CSS3 course can be boring at times, at least it was for me. :)
I made a Dungeon Generator in python that takes some input from the user (a seed, size, etc) and returns an image. I would like to make a single page website that would run the script but have no idea how to go about doing that. Any pointers on picking a framework or useful tutorials on how to set it up?
Some people recommended Django but I'm overwhelmed just looking at it, no idea where to start or what to do to make this happen.
Thanks!
isn't flask recommended for beginners? there's always this flask tutorial: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
Flask and Django are both fine for beginners in my opinion, it's just that Django looks more intimidating because it throws everything at you at once whereas Flask you have to assemble yourself so you get a feel for it as you go but if you just start with the Django beginner tutorial it breaks it down into smaller more manageable pieces to learn, just as the flask mega tutorial does.
Hello everyone,
hi
i have a problem in my code, im using django.. im trying to implement comments but im getting the error "'Poll' object has no attribute 'get_absolute_url'"
heres my code
@login_required
def poll_detail(request, poll_id):
#poll = Poll.objects.get(id=poll_id)
poll = get_object_or_404(Poll, id=poll_id)
comments = Comment.objects.filter(post=poll).order_by('id')
user_can_vote = poll.user_can_vote(request.user)
results = poll.get_results_dict()
if request.method == "POST":
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid():
text = request.POST.get('text')
comment = Comment.objects.create(post=poll, user=request.user, text=text)
comment.save()
return HttpResponseRedirect(poll.get_absolute_url())
else:
comment_form = CommentForm()
context = {
'poll': poll,
'user_can_vote': user_can_vote,
'results': results,
'comments': comments,
'comment_form': comment_form
}
return render(request, 'polls/poll_detail.html', context)
why dont you try reverse() function and see if it fixes the issue
Hey, I am going to build a site however, I have 2.4TB database with sqllite to host. This is expecting to grow 10% a year. Anyone help me out with what type of requirements it would take if I were to use a cloud service?
Umm, switch to a better database backend.
I don't even know how sqlite likes that big of a database.
So the data I need is already done inside a database. Iโm just downloading it and then updating it monthly with the new data, the website is going to query the data
I donโt think I could move the data to new database easily anyways
So do you plan on hosting the site with the large database in the cloud?
from flask import request
from flask_restful import Resource
from models import db, Discord_Users
class UsersResource(Resource):
def get(self):
value = request.args.get('user_id')
if value is not None:
query = db.session.query(Discord_Users.user_id, Discord_Users.permission_granted) \
.filter(Discord_Users.user_id == value) \
.one()
return {'status': 'success', 'data': query}, 200
else:
return {'status': 'failed', 'message': 'This is not how it works'}, 400
How do I fix the error as it says: TypeError: Object of type datetime is not JSON serializable?
Does your query have a datetime in it?
Yes.
That's probably why
Discord_Users.permission_granted has a datetime in it.
And I want to output that datetime too, but in json.
You might need to pass through your query and turn that datetime into a string
You can't output a datetime and a lot of other models via JSON
Hmm, then how would I get the same kind of json layout when using that {'status': 'success', 'data': query}, 200 if I were to use jsonify?
Is query a dictionary right?
Can someone help me connect ReactJS to Django?
especially nodeJS problems
but i think i will try to use rest_framework even though i dont understand it yet
I'd definitely recommend separating things, like so: #004990
Er
One sec
Like that.
DRF is not too bad to get into. The quickstart guide isn't bad: https://www.django-rest-framework.org/tutorial/quickstart/
Django, API, REST, Quickstart
And there are some other okay resources around (https://medium.com/backticks-tildes/lets-build-an-api-with-django-rest-framework-32fcf40231e5)
There's two schools of thoughts on getting started - you could start with React and then make a dummy API for mocking data, and then model your API on the dummy API
Or you can make the API first.
How much experience do you have with consuming / using APIs?
huh
Hmm, I'm myself among those who use Flask. :D
!warn 390556291766157323 please keep the help channels on topic
:incoming_envelope: :ok_hand: warned @quasi wedge (please keep the help channels on topic).
That took a while
yes python is a bit slow today. We have top men working on it
Needs more hamsters!
Is it a good idea to switch from flask_restful to flask_restplus?
If I want to use flask_restplus with swagger documentation, how do I specify them to my resource classes?
How do I set the definition?
is there a way to do a text box in css
are there any free recent tutorials on building APIs with flask?
I want to integrate my react frontend with a flask backend for CRUD'ing a database
@dull ginkgo textbox in CSS? You mean styling a textarea element?
@sweet wharf are you sure you imported it correctly
import React, {Component} from 'react';
import ReactDOM from "react-dom";
const app = document.getElementById('app');
class App extends Component {
render() {
console.log(ReactDOM)
return <h1>React App</h1>
}
}
ReactDOM.render(<App />, app);```
this is the code im trying to run
and i get this error
i tried importing ReactDom but i get the same error
can you log the reactdom before the render
I tried that aswell but i get the same error. it wont log
and you did rebuild after making the changes?
and is react-dom defined correctly in the webpack config
I did not build the project yet. I use "dev": "webpack --mode development ./frontend/src/index.js --output ./frontend/static/frontend/main.js", command
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
}
}```this is my wp config
wait nevermind i feel soo stupid now
thx for you time anyways
what was the fix?
I forgot to put --watch in the script so i needed to reload everytime i made a change in the js file
how do i make text in an input box bigger
css:
style="font-size: 24px;"
thank you!! @ivory pagoda
Could people help me out?
1 vote and 1 comment so far on Reddit
Hey anyone know why when I make an input thing it puts the box then the text
I want it like (text) ( then enter box) but it does the opposite
tag me if u respond so I know someone answered plz
what html are you using and what css do you have? why its happening can vary wildly because of that stuff @native tide
might want to use the web browsers inspector to see what css and such is impacting your components
so its likely due to whatever css you have
is that all of your css or are you using something like bootstrap that adds a ton of defaults?
sometimes they are set up in a way that requires you to use a specific tag for input labels
that isnt all that is all that would be effecting the container here ill send a pic of all
id prefer it in text form tbh so i can copy paste and test stuff
@native tide sorry about that
you triggered our newlines rule
if you could please upload your CSS to https://paste.pydis.com/
srry my b ok
I just dont see anything that would make it flip out like that on my page.
with what you provided so far it puts the text first :
oooooo I didnt add a break after one of them and I thought it was puttting it first
my apology
thank u tho
haha no worries
i always need to add css .container { padding-top: 15px; }
when dealing with bootswatch because text gets too close to navbar for comfort
is there way to get a context variable with something like {{ user + i }} where i is a variable in a for loop
and user is part of the context
some web frameworks have a built in way to manage a 'list' of items in a form that all have the same name
oops probably should have managed its django
anything more specific to django like that or not sure? ive been looking around
alright. ill do some digging in the docs
looks like people are suggesting that you instead use a dict or list
rather than naming them all similar stuff
and then the templates have a built in looping system that you can use
ty
I was looking at a dict as the first thing but i didnt know thatd work
but ill take a look
that actually might be exactly what im looking for. thanks!
:>
yeah it was dot notation in a template but i thought of the normal way with like key[value]
so that clears a lot up lol
If my project structure is like this:
.
โโโ app
โย ย โโโ __init__.py
โย ย โโโ main
โย ย โย ย โโโ config.py
โย ย โย ย โโโ controller
โย ย โย ย โย ย โโโ api_user_controller.py
โย ย โย ย โย ย โโโ auth_controller.py
โย ย โย ย โย ย โโโ discord_users_controller.py
โย ย โย ย โย ย โโโ hello_controller.py
โย ย โย ย โย ย โโโ __init__.py
โย ย โย ย โย ย โโโ messages_controller.py
โย ย โย ย โย ย โโโ profiles_controller.py
โย ย โย ย โโโ flask_boilerplate_main.db
โย ย โย ย โโโ flask_boilerplate_test.db
โย ย โย ย โโโ __init__.py
โย ย โย ย โโโ model
โย ย โย ย โย ย โโโ api_users.py
โย ย โย ย โย ย โโโ blacklist.py
โย ย โย ย โย ย โโโ channels.py
โย ย โย ย โย ย โโโ discord_users.py
โย ย โย ย โย ย โโโ __init__.py
โย ย โย ย โย ย โโโ messages.py
โย ย โย ย โย ย โโโ profiles.py
โย ย โย ย โย ย โโโ users.py
โย ย โย ย โโโ service
โย ย โย ย โย ย โโโ api_user_service.py
โย ย โย ย โย ย โโโ auth_helper.py
โย ย โย ย โย ย โโโ blacklist_service.py
โย ย โย ย โย ย โโโ discord_users_service.py
โย ย โย ย โย ย โโโ __init__.py
โย ย โย ย โย ย โโโ messages_service.py
โย ย โย ย โย ย โโโ profiles_service.py
โย ย โย ย โโโ util
โย ย โย ย โโโ decorator.py
โย ย โย ย โโโ dto.py
โย ย โย ย โโโ __init__.py
โย ย โโโ test
โย ย โโโ base.py
โย ย โโโ __init__.py
โย ย โโโ test_auth.py
โย ย โโโ test_config.py
โย ย โโโ test_user_medol.py
โโโ configs
โย ย โโโ app.ini
โย ย โโโ test.ini
โโโ Dockerfile
โโโ Makefile
โโโ manage.py
โโโ migrations
โย ย โโโ alembic.ini
โย ย โโโ env.py
โย ย โโโ README
โย ย โโโ script.py.mako
โย ย โโโ versions
โย ย โโโ 0b60d1b2676f_more_tables.py
โย ย โโโ 63aa1eb343ec_more_tables.py
โย ย โโโ fd6a303ce8d4_initial_database_migration.py
โโโ README.md
โโโ requirements.txt
what do I set in uwsgi config as callable?
cat app/main/init.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_bcrypt import Bcrypt
from .config import config_by_name
db = SQLAlchemy()
ma = Marshmallow()
flask_bcrypt = Bcrypt()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config_by_name[config_name])
db.init_app(app)
flask_bcrypt.init_app(app)
return app
That's the one that should be the callable right?
That's not callable
Basically uwsgi wants you to give it a module that you can run that will end up with a WSGI app object at module level
your create_app isn't being run with the result stored in that module - so it's not correct
you could use eg ```py
if name == "main":
app = create_app(...)
then refer to your app.__init__:app
I think a lot of projects use an app.py or __main__.py for this though - in which case you'd have either app.app:app (lol) or just app:app respectively
@hollow flower
i go the django route and create an extra wsgi.py file where i just instantiate the app
Ah, yeah, I forgot about that, that's a fairly common approach too
does django use pure jinja for templating?
It uses the django templating language
jinja is kinda inspired by it, so it looks similar, but it's not the same
i thought django came after jinja?
huh
well my navbar if statement works fine across django and flask so im happy enough with that
You should avoid trying to do that with your templates, really
Each templating system has its own quirks, and you need to make use of them to get the most out of them
how do you make it highlight then
in what?
navbars
with a CSS class?
I don't understand your question
okay, but don't rely on that
if you have a flask app and a django app then they should have their own templates :P
yeah its only for highlighting the navbar things
No, you're missing my point
If that changes between versions of either flask or django then it'll break
yeah
You need to be maintaining the templates separately
i done it once on django and ported to flask
Also, django and flask don't use the same template inheritance stuff
thats the bit i changed
You shouldn't be copy-pasting your navbar code into each template, so you need to think about that as well
anyway, you get my point
@meager anchor I don't even know what is the django route as haven't used it.
If I want to display results of my web scraping code to my website
What should I do?
Like making a simple web scraping using requests
And bs4
After that I click a button on my website and it sends a request to my web scraping script and it returns back and shows the results
I'm lost lmao, people say use a framework like flask or Django but I think that would be overkill
Think we concluded it was, barely
@knotty lark if you can answer, I'm sorry to bother you
@plain solar going to have to ask you to change your profile picture if you want to remain a member here. It does not comply with our NSFW policy
I'd rather that be shorter if possible.
I'm running to an issue where it seems like django runs what's inside the if clause even though the condition is not met inside the template
Anyone knows if this is just the case, like
Everything inside the template renders even if it is not meant to be end up in the finale html that is being served
@Helpers damn, damn, damn
Can't even ping helpers
You're not supposed to be able to ping helpers; people will help when they think they can and/or have time
In your case, it would probably help to have code and an example of your data
Without that, it's pretty difficult to help
{% if entry|after_count !=0 %}
<a href="{% url 'entry' entry_pk=next.pk %}?order={{order}}" class="showall more-data" title="tรผmรผnรผ gรถster">{{entry|after_count}} more entry</a>
{% endif %}```
I come from a time when you can ping helper btw
Where entry|after_count is 0, I get NoReverseMatch
while it shouldn't even try
Nevermind, wrote it in a different way
@plain solar you have 10 minutes to comply.
@kind steppe K cool?
Thank you
K
thats my code for my website, if i hover over a button it drops every content
in the first picture im hovering over school
second im hovering over entertainment
third im hovering over games
and im also hoping to find an answer on how to align them under the text
note im quite new to html and css so im extension in my class and my teacher doesnt help extension kids and its really fucked but.. yeha
ping me if u can help
Itโs all about the stylesheet
Your titles arenโt boxed
There are lots of open-source flat dropdown-menuโs to check out, check the source by pressing F12 & learn from it
how can I create a GET request only using sys and socket?
I'll get API key and parameters as program arguments
Over HTTP or HTTPS?
HTTP
Alright, HTTPS would be almost impossible without another module. How do you need to send the API key?
what do you mean?
Is it in some kind of json, a param, authorization header?
I'm making a script which creates a socket and connects to openweathermap, then as program argument I get an API key and city's name
then it'll print the info to console
well, I assume it's an auth header
Can I ask why you didn't use requests or urllib?
I can't
http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=b498767252de12f92504d2cca9c3fdc1
should look sth like this
You can't, for like a challenge?
yes
I think sending data like "GET http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=b498767252de12f92504d2cca9c3fdc1\r\n" should suffice
though I have to admit that networking is not something I know well
Do you know how to create sockets?
I've already googled how to create socket and connect to API
I've done that, but now I'm stuck here
let me get sth straight: http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=b498767252de12f92504d2cca9c3fdc1\r\n is the request itself?
Wait, I'm so wrong lol, one sec
def create_socket():
try:
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print("Failed to create socket. Exiting...")
sys.exit()
print("Socket created!")
return mySocket
def connect_to_api(mySocket, ip_address):
try:
mySocket.connect((ip_address, port))
except socket.error:
print("Failed to connect to API. Exiting...")
sys.exit()
print("Succesfully connected to API!")
return
I started with python like 2 days ago
this is sth I've put together from a bunch of examples
First, you'll need to get the site's ip,so put the website domain (without http) into socket.getaddrbyhost
Oh, maybe it does it automatically. Once, you connect like with ("api.openweathermap.org", 80) (port 80 is always used for http.
yes, I've read that somewhere and use it
So 2 things.
You don't need a socket connection, it's done with regular http requests
And you should never post your api key anywhere
I think what you actually want to send is GET /data/2.5/weather?q=London,uk&APPID=b498767252de12f92504d2cca9c3fdc1\r\n
it's a non-functional key
dw
what does the \r\n mean at the end of request?
newline?
It's to signify a new line, yeah
requests is a great library for what you are trying to do
Not 100% sure however I'm fairly certain HTTP requires a new line at the end
Yeah, it worked. Would you to see the code?
sure
You can only send bytes into a socket. String that start with b aren't strings, but bytes
So, yeah
This is different if you're using python2 though, then you only need to send strings
i use 2.7.15
Ok, then don't use b, otherwise I think it's the same
I see, thank you!
I got a bit further (thanks to you), but now I'm getting 400
any ideas where the mistake could be?
my_api_key stands for my personal key, only the printout is changed
at the end of request is \r\n
mby the real problem is specific to the page's API?
well
the problem was that I didn't put GET in front of the request
end me
We've all been there ๐
anyone recommend a good tutorial or online resource in learning django?
https://canary.discordapp.com/channels/267624335836053506/303906514266226689/545145165631717416
It wasn't solved there, but could anyone possibly help me with this?
I ran the tutorial but for me it stops at a Middleware error
I did read some of those suggestions as well, got me confused at first.
Actually this case has been addressed in the tutorial.
So it's not the source of the problem.
so.. lets unpack what you have done so far
you pip installed everything and then you cloned the git repo? right?
@frigid egret
Yes
then what did you do then?
then you ran the migration and then ran the server?
And after making sure it works fine, went straight for /admin
Yes, I did run migrations as well
uploading worked?
Since I still don't know when not to use it, I use it more often than I should XD
Yes, uploading on both /polls and /polls/import works fine.
Can you send me your project so I can try and run it?
how do you start the server? from where
terminal
you liked a folder structure earlier, is that something you use?
py manage.py runserver
from django-excel ?
Uh, the whole file? It's quite long for direct text.
Can't upload it as a file. I guess role restrictions.
no from instaslled_apps to root_URL
wait, hold on
Wrong one
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware'
)
ROOT_URLCONF = 'mysite.urls'```
ahh.. I was about to say so
There was a change with MIDDLEWARE_CLASSES some time ago, so when I thought you where using an older version I added this
Im sure you just need to rename it to MIDDLEWARE
you might have to run the migration again
so change that and run try to access the admin page
@frigid egret
trying rn
Yay, it works!
Thank you!
Is it because I was using a different version?
yes, version conflict with the tutorial
it was as I suspected from the beginning, but I have limited experience with django so I had to "figure" the solution out myself.
glad it works for you @frigid egret
Hello, I have issues with django app using django rest framework, specifically with unicode characters error while trying to save request_data to database.
While in request headers there's no unicode characters, it saves it just fine, but if it has one unicode characters postgres psycopg2 throws error
DataError: invalid input syntax for type json - DETAIL: Unicode low surrogate must follow a high surrogate.
Serializer
class DecisionSerializer(serializers.HyperlinkedModelSerializer):
headers = serializers.DictField(required=False)
class Meta:
model = Decision
write_only_fields = ('headers',)
fields = ('headers',)
def create(self, validated_data: dict) -> Decision:
site = validated_data['site']
request_data = self.context['request'].data
site.decision_set.create(allow=False, request_data=request_data)
Model
class Decision(models.Model):
request_data = JSONField(default=dict)
Settings.py Django rest framework settings
'UNICODE_JSON': False,
'STRICT_JSON': True
I'm lost because it should not allow any unicode characters to pass through, but still they got past my settings and throws DataError.
so i ve made a script using sendgrid Api
i ve created a django app
i ve created a form in that
i want that it takes values from form
and put that in the script
and run that on submit buttonhanks in advance
What's wrong with this?
var fbutton = document.evaluate("//input[@type = 'submit']", document, null, XPathResult.ANY_TYPE, null);
document.fbutton.submit();
/* Style The Dropdown Button */
.dropbtn {
margin-right: 300px;
background: transparent;
color: #ff2a7c;
padding: 16px;
font-size: 30px;
border: none;
cursor: pointer;
}
/* The container <div> - needed to position the dropdown content */
.dropdown {
position: relative;
display: inline-block;
}
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
background: transparent;
min-width: 107px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
/* Links inside the dropdown */
.dropdown-content a {
max-width: 30px;
text-align: right;
color: #ff2a7c;
padding: 12px 16px;
text-decoration: none;
display: block;
}
/* Change color of dropdown links on hover */
.dropdown-content a:hover {
color: #5deadc
}
/* Show the dropdown menu on hover */
.dropdown:hover .dropdown-content {
display: block;
}
/* Change the background color of the dropdown button when the dropdown content is shown */
.dropdown:hover .dropbtn {
background: transparent;
}
my container seems to be too far open and i cant get it lined up with school
if i do <p align='left'</p> it aligns but then its not inside the header
and if i do max-width it cuts off from the right hand side
please ping if you can help me
Does anybody have a good non video tutorial for a database efficient way to sort and search a large table? It can be fairly technical, as anything I don't know in the article I'll just go learn. Just been stuck for a few days. Python 3.6, Django 2., MySQL.
Cross posted in the database channel as well. If there is a better place than here to ask this question, please let me know. Thank you.
@outer marsh i think best database efficeient way is to make some store procedure and call it
Hi, how to receive data of post request in flask?
I have a search bar on my website, is there some way to automatically input data into that search bar if the user starts typing even if the search bar isnt selected
just jquery or something?
Solved it, ty for help
hmm, i want to make gameserwer , my plan was to put it behind ngnix, 1.AuthRegFlask , 2.AdminLobyMatchmakingFlask ,3.Have multypele insances of Websocket games (probbaly in C++)/or can do Flask-SocketIO, so my main question is can i dynamicly change Ngnix rev proxy to target my GameInsances from "AdminLobyMatchmakingFlask" ?
Hey guys, I am installing flask using https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04
im on step 4 running gunicorn --bind 0.0.0.0:5000 wsgi:app and receive ImportError: cannot import name 'app'
trying to use request to load a page that works in chrome but I can't connect in requests
requests.exceptions.ConnectionError: ('Connection aborted.', TimeoutError(10060, 'A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond', None, 10060, None)) Anyone have any idea what kind of things I need to look into to set it up
What does your code look like? @floral fulcrum
think there are some networking issues but I am not very familiar with networking
Oh I figured it out
I have to use a different SSL protocol to connect and requests doesn't do that automatically
New to webdev but other than sqlite what other ways could I store data that python can access?
sqlite is only one of many different kinds of databases and python can access data in many ways
it depends on what you are doing
Hmm at the moment I'm trying to create a place where a user can login then get redirected to place where they can choose the courses they want to take. For example username: Adam
password: hello123
courseOptions: English, Maths, Science
email: hello@hello.com
hmm , should i use Server side session with flask or what to prevent auth spam, like 3 trys chill 20min
that or myeb to do it form DB
hmm i could do it form DB but that whay somone can spam my DB and i dont want that, so i need to set this flask but using ServerSideSession Flask-Session , right? i just tryed that but it alwies crys
"RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret."
even i added app.secret_key = 'some secret key'
using clinet side session in cookie worked np, but i want serverside
anyone?
Anyone use flask? When I change code it doesnโt update unless I reboot
app.run(debug=True)
I have that set to true in both the main file and wsgi
i have a .ini file that runs a flask website that streams videofile via opencv. It runs perfectly when I use uwsgi app.ini. Then I deploy it in my emperor.uwsgi.service. The static websites are fine, but when I go to the streaming page, All the text/headers are in position, but the "video" won't stream/show. The page is saying waiting for 192.168.1.38.... What settings should I add to my emperor so that it will also auto refresh the page, because the streaming part of flask is just a Response that changes the image every second.
I'm kind of wondering why you're using emperor
when uwsgi will do workers for you
unless you're going with like a big distributed webapp
The best hint to this may actually be in your browser's console
Its actually not a big problem, I just want to use it in systemd enable emperor.uwsgi.service so that uwsgi will autoplay everytime I turn on my Pi. Is harakiri not related to my problem?
I've actually not used emperor, that's why I ask
if you put your uwsgi config in uh.. I think it's /etc/uwsgi/
I think you can use the uwsgi systemd service
eg if your config is named app then you just enable uwsgi@app.service
but either way, emperor should work fine, assuming it and its vassals are all configured correctly
as well as nginx or whatever webserver you're proxying with
!tempmute @abstract orbit 6h spreading chain mail in an on topic category
:incoming_envelope: :ok_hand: muted @abstract orbit until Sun, 17 Feb 2019 07:02:45 GMT (spreading chain mail in an on topic category).
can anyone recommend flask or django or something else?
I just want to make a moderately simple site for showing some sports statistics like outputting MySQL to tables in webpages
I need to make a choice for some "quick and dirty" prototyping I just wanted to see what the general coconscious is on bottle vs flask. I have not really worked extensively with either. When I say prototyping I mean there doesn't need to be auth or anything as it is all going to run local and is for demonstration purposes only
Bottle vs Flask: They both have a very similar API. Bottle's only advantage is that it's a single file that you can include alongside your app, whereas flask really needs to be installed with pip.
If you don't care about that, use flask.
๐ :
Can anybody here guide me how to package my flask app as an single file executable on mac
single file executable of a flask app? what's the grand goal of this?
Just wondering does {% block body %} {% endblock %} specify <body> </body>?
Depends on your templates.
But generally no, it's just a block with the body name. It does not magically add any tags for you.
Ah ok
Looking for some guidance to start hunting down a root cause. I can access a WSGI application when i launch gunicorn via SSH, and open a test port (8000). And i can access the nginx server that is running and listening on port 80. So i know both the Gunicorn and nginx are functioning correctly... But they are not functioning together. When i configure a new service to bind the nginx and gunicorn to the sock file it Doesnt create it/gunicorn cannot access it. The folder that should have the sockfile
/var/run/
has +775 using www-data : www-data. Running ubuntu 18.04. Any suggestions on things to check would be fantastic.
[
{'a': 1},
{'b':2},
{'c':3}
...
]
How would I get an array of ['a','b','c' etc..] from this with JS?
I posted sth, but haven't read to the end the thing about JS
Figured it out. array.map(d => Object.keys(d)[0])
What's a way to validate emails other than using regex? I've tried validate_email but it doesn't for all emails.
validating email is overrated
just send an email
the mailer won't accept it if it's invalid
(what problems are you running into with validate_email)
I've got a school email that ends with .org.uk and it returns None. Got me thinking what other emails would not be valid
And sending an email kinda like saying hey click this to validate your account ?
yep
its the only real way to be sure. you can check for an @ symbol if you really want but trying to regex that its valid or anything is just a waste of time and will annoy people with a weird email address
if they dont click it after a certain amount of time just delete their account
...honestly i looked at the code to validate_email and it looks pretty rigorous
well i think most of the issue is trying to use regex specifically, but again it doesnt really matter since what you really want to know is if that email can be used to contact and identify that specific user
>>> validate_email.validate_email('foo+bar@example.org.uk')
True```
also what do you mean it returns None? validate_email returns True or False, not None
looks like validate email can check if the email servers dns entries exist which is pretty cool
@fossil lotus
or if the mail server is actually there AND it accepts the email, thats interesting
so it does have an alternative to actually sending the email. but it wouldnt surprise me if its basically 99% of sending an email
of course without sending it and making the user click it you dont really know whos email address it is still
Ahh sorry didn't clarify
for most purposes you'd use an email for you'd want to confirm that the user who typed it in actually owns the address, which is where sending an email comes in
yeah imo there is no reason to even take the users email if you dont intend to send something to it
just use a username instead
try validate_email.validate_email('foo+bar@example.org.uk',verify=True) You will need Py3dns
and I'm using emails in case they forgot their password
If they need a password you want an email
Sry didn't see that
validate_email.validate_email('foo+bar@example.org.uk',verify=True)```
makes sense, but i would still send them an email to make sure it works
validate_email gets you most of the way though
Yeah that's true I guess I can say if you entered a wrong email an admin account can reset / change it ?
hmm if its their login name too
then i would just delete the account tbh and let them recreate it, since odds are they wont be able to remember the login if they typo the email
you might have an initial login just via cookies that they can use to try to save the account
Oh no they login with a username
eg like your email hasnt been verified so please fix that in a big red box at the top of pages
ah
yeah then just ask them to verify/fix the email
@fossil lotus turn debug on
debug on where?
>>> logging.basicConfig()
>>> validate_email.validate_email('foo+bar@example.org.uk',verify=True, debug=True)
i get DEBUG:validate_email:ServerError or socket.error exception raised (timed out).
maybe py3dns is broken?
hmm I think I'll just make it to admin can manually reset the email account.
oh wait duh
example.org.uk probably isn't accepting connections
you can still turn verify off and use it to validate the syntax of emails, i'm thinking the check_mx/verify stuff maybe isn't very good
Yeah I wanted to verify the emails initially but moving away from that and just verifying syntax
@fossil lotus a general question for you, what will you do to verify that the user is the right person?
eg lets say i am a bad guy and see that a new user was created, so you prob have not yet sent them an email.
what stops me from asking the admin to reset my password and claiming i typoed the email address?
its a consideration if its a big / serious site
but not a big deal on a private site where you dont expect a lot of traffic
Ughh it's for a school project so don't need to worry about that
haha
yeah im not sure how you would solve this problem easily if you want to skip verifying the email
which makes sense for your school project
Well being honest all I had to do was make a website that showcases what computing and IT courses my school offers but wanted to add some functionality to the website which will help the teachers during an open day.
but in general, i guess you would have to ask them for something only the account owner would know.
like on steam they can ask what games you had i guess
Rn I'm thinking the student will sit at a computer during the open day make an account with the help of a teacher and do what they want.
Yeah I guess so could get a timestamp i.e when a student signs in for the open day and get them to store it or something like that.
[2019-02-18 23:46:30,340] ERROR in app: Exception on /api_users/registration [POST]
Traceback (most recent call last):
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_restplus/api.py", line 329, in wrapper
return self.make_response(data, code, headers=headers)
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_restplus/api.py", line 350, in make_response
resp = self.representations[mediatype](data, *args, **kwargs)
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_restplus/representations.py", line 25, in output_json
dumped = dumps(data, **settings) + "\n"
File "/usr/lib/python3.7/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/usr/lib/python3.7/json/encoder.py", line 201, in encode
chunks = list(chunks)
File "/usr/lib/python3.7/json/encoder.py", line 438, in _iterencode
o = _default(o)
File "/usr/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type MethodViewType is not JSON serializable
api_users_service.py: https://pastebin.com/yqB3FSSG
api_users_controller.py: https://pastebin.com/0Ls7CEYN
Umm, ideas?
the error message seems to indicate that you passed an object of type MethodViewType someplace you were not supposed to in the function ApiUserRegistration.post
also both pastebins have the same code in them
its possible the way you are mapping apiuserregistration to your view is wrong but i cant see any other code
I see. I actually did find the error. I was using a class when I was ment to be defining a function rather.
I know I've been asking a lot of questions lately but bear with me. How do I make it so that an admin can type a username click submit button and it comes up with the necessary sqlite db information under the button.
Also is it possible without passing username like this /foo?username=bar ?
Nvm managed to do it ^^.
flask_jwt_extended.exceptions.NoAuthorizationError: Missing Authorization Header
What would be the best way to catch that error?
Does anyone here know any good resources for django?