#web-development
2 messages · Page 16 of 1
Is that your domain?
I don't know what that is
Ah
Tests a connection
Can just test using your phone
so to make a web page visible on the internet you need a domain name, with dns that points to your ip, a firewall with the right ports forwarded, and a server running on those ports
http://<your-public-ip>:5000/
to make it visible to normal people that is
Replace <your-public-ip> with whatever your public IP address is (google will tell you)
normies arnt gunna type in an ip address, but if you dont mind you can yourself
That's to make sure the port forwarding isn't the issue
My troubleshooting strategy tends to be start in the middle and split the search space, just like a binary search 😉
Saluton!
Howdy guys
@marsh ginkgo what's the point of having computer languages? We should all just write everything in 0s and 1s. There is obviously an improvement somewhere..
@native tide Do dm me if you would like to work on something..
guys how do I go about changing a overlay position when it goes ouside the viewport. I have a hover effect in some gallery which shows info about the item. In mobile or small viewport last item hover goes off screen and its not readable
is there anyway to change its position or force it inside the main div
So i have a question guys not sure if this is the write place to put it but i want to learn to use Django but i don't have an experience in python programming should i do a course on python first then one on Django or should it be fine to jump straight into Django.
@rustic aspen Depends on your learning style I'd say. I'm going the python first, then django so I'm able to tell if an error I'd get is python syntax related or something w/ the django specific stuff.
Yeah i was wondering if it would have a negative effect on me if i tried to use python for non web related stuff
Well python isn't web specific, you can make software/games using it as well
I think i might just learn at least the basics and OO python before i move onto a framework just to make sure that i have an understanding of how the language works that way i wont get screwed over when i try to branch out of web dev
Can someone explain CORS to me like I'm 5. I can't seem to wrap my head around it.
I'm trying to setup a very simple restful API with Flask and my app requesting from it keeps getting it's requests blocked by cors
import requests
from flask import Flask
from flask_restful import Api, Resource
from flask_cors import CORS
app = Flask(__name__)
api = Api(app)
CORS(app, origins="http://127.0.0.1:3000", allow_headers=[
"Content-Type", "Access-Control-Allow-Credentials"
])
class Reddit(Resource):
def get(self, subreddit):
response = requests.get(
f"https://www.reddit.com/r/{subreddit}/top.json")
status = response.status_code
if status == 200:
return response.json(), 200
return "No result", status
api.add_resource(Reddit, "/reddit/<string:subreddit>")
app.run(debug=True)```
The request itself (in js) ```js
const top = http://127.0.0.1:5000/reddit/${subReddit};
const response = await fetch(top, {
method: "GET",
mode: "cors",
headers: {
Accept: "application/json"
},
});```
@olive wharf this one explains it really good https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
in your case I suppose the problem is that you specify allowed origin with port 3000 while you are performing requests on port 5000.
I've tried both ¯_(ツ)_/¯
can you somehow check the response headers that you are getting in your JS?
Uh, I can probably log it
Nvm, It returns when doing the request
So i dont have a response to check in this case
? does it fail on JS side or Python side?
js
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:5000/reddit/srg. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘localhost:3000’).[Learn More]```
hang on thats different than before
I'm more or less Frankensteining what I can find at this point
Again, I tried both
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:5000/reddit/asd. (Reason: CORS request did not succeed)```
import requests
from flask import Flask
from flask_restful import Api, Resource
from flask_restful.utils import cors
from flask_cors import CORS
app = Flask(__name__)
api = Api(app)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
class Reddit(Resource):
def get(self, subreddit):
# esponse = requests.get(
# f"https://www.reddit.com/r/{subreddit}/top.json"
# )
# status = response.status_code
# print(response.text)
status = 200
if status == 200:
return {"data": "lol"}, 200
return "No result", status
@app.after_request
def add_cors_headers(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Credentials', 'true')
response.headers.add('Access-Control-Allow-Headers', "X-Requested-With")
return response
api.add_resource(Reddit, "/reddit/<string:subreddit>")
app.run(debug=True)
``` Is what I'm at atm, but still getting ```
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ‘http://127.0.0.1:5000/reddit/all’. (Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’).```
@olive wharf I've never done it in Flask but assume it is the same.
You need to respond to the "Pre-flight" check.
The way it works is like this:
JS will check every GET request. If the GET request includes "restricted" headers, it will FIRST do an OPTIONS request to the same URI.
The Options request will NOT include the restricted headers (usually Auth headers).
So you need a handler that responds to the OPTIONS request and tell the client that it is OK to send the headers.
The JS client will then go ahead and make the normal request.
It might be necessary to add a request handler for the options request to the Flask app.
class Reddit(Resource):
def get(self, subreddit):
# esponse = requests.get(
# f"https://www.reddit.com/r/{subreddit}/top.json"
# )
# status = response.status_code
# print(response.text)
status = 200
if status == 200:
return {"data": "lol"}, 200
return "No result", status
def options(self, **kwargs):
# Set a return status
# Add the CORS headers to the response
return response
Have a look here:
https://stackoverflow.com/questions/26980713/solve-cross-origin-resource-sharing-with-flask
For the following ajax post request for Flask (how can I use data posted from ajax in flask?):
$.ajax({
url: "http://127.0.0.1:5000/foo",
type: "POST",
contentType: "application/json"...
Shoulda updated my post, but that's not quite needed
import requests
from flask import Flask
from flask_restful import Api, Resource
from flask_restful.utils import cors
from flask_cors import CORS
app = Flask(__name__)
api = Api(app)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
class Reddit(Resource):
def get(self, subreddit):
response = requests.get(
f"https://www.reddit.com/r/{subreddit}/top.json",
headers={"User-agent": "Top posts from reddit bot"}
)
status = response.status_code
if status == 200:
return response.json(), 200
return "No result", status
api.add_resource(Reddit, "/reddit/<string:subreddit>")
app.run(debug=True)
``` is what i ended up with
It was half n half fault along with sending bad headers with my request on the client side
I'm getting AttributeError: 'str' object has no attribute 'get' with this class-based view:
class SignUpView(FormView):
template_name = 'signup.html'
form_class = SignUpForm
success_url = reverse_lazy('email-confirmation-sent')
def form_valid(self, form):
self.object = form.save(commit=False)
user = self.object
user.is_active = False
user.save()
current_site = get_current_site(self.request)
subject = 'Account Verification'
message = render_to_string('email_confirmation_content.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
'token': account_activation_token.make_token(user),
})
send_mail(subject, message, 'admin@quizy.com',
[form.cleaned_data['email']])
return super().form_valid(form)
but when it's used within a normal view everything's ok
Can I ask a D3 question here, or is there a better place?
Any ideas as to how I might be able to use the Flask Werkzeug debugger and hot-reloading functionality alongside another remote debugger, such as pdb or ptvsd?
Not being able to touch signals in non-main threads is really biting me atm
I now need help
is anybody there?
so
I am using flask and jinja2
and I have a template
<html lang="en">
<head>
{% block head %}
{% endblock %}
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>```
Which is erroring
Hello?
Hello
I think you don't need to use body and head block when you don't write anything in it
Leave it empty
And try
I hope it runs okay😅 🤔
@ornate crest
@deft lagoon not sure you understand templates. blocks that you don't write anything are an important part of writing a good website that uses templating
the template looks fine, what kind of error are you seeing @ornate crest
@deep cave
yo,
so
wtf
reee
okay so, i got json database.
with open('watchlist.json', "r") as f:
newuserdata = json.load(f)
newuserdata[user] = id
with open('watchlist.json', "w+") as f:
json.dumps(newuserdata, f)
what if i wanted to erase newuserdata from the database
is it web development?
it has to do with json,
asked where i could put this in #databases
they told me here
okay
so
that is clearly a nonserious question
please be serious
offtopic probably goes in one of the ot channels
@harsh iron do remove a key, just do del dict[key]
In future, any of the help channels are suitable for this sort of question
as well as python discussion and OT
but like newuserdata is the database
newuserdata is what's being added to the db
It claims I need an endblock
I am ending all my blocks though
@deep cave
ya sure?
please ping me
I am in 34 servers and cannot have notifications on all
so @ me if you respond
I'm getting a permission error from nginx while attempting to run uwsgi sock file
How do I get around this permission error?
@ornate crest you need to actually show us your code if you expect us to be able to help. that traceback isn't helpful without seeing all the files it mentions. shell.html an login.html are probably culprits, my money is on login.html.
{% block head %}
{{ super() }}
{% endblock head %}
{% block body %}
{{ super() }}
<form action="POST">
Password:<br>
<input type="password" name="pass">
</form>
{% endblock body %}```
should be just {% endblock %}
why are you even calling super() if there's nothing in the blocks in shell
well there's going to be a title and a footer
well this also is valid jinja.. but I've never tried to do a super and nothing else in a block that extends another empty block, since that's pointless. maybe it makes it weird up. why don't you put some stuff into these blocks just to see if it changes anything.
same error
eh. forget to save the file? caching issue?
shouldn't crash with that error based on your templates.
2x
and hard refresh the page
yes
and actually make sure you've saved the templates
yeah fine. debug it then. use pdb or something
File "/home/ray6y/soup/Reindeer/templates/shell.html", line 7, in template
{% block body %}
I mean use a debugger and figure out why it thinks there's no endblock.
ok
your code looks fine. I don't know why you're getting a mysterious error that doesn't apply to your code. dig into it with a debugging tool and figure it out. best you can do at this point.
thanks
stepping through it with pdb would allow you to print the stuff flask is parsing and figure out what it looks like. might shed some light
the pycharm debugger would work, too
pdb does not like flask
wait what
<head>
{% block head %}
</head>
<body>
{% block body %}
</body>
</html>```
not sure where it's getting that from
that is not the layout of my code
Does anyone here know about web-scraping?
A man needs some aid logging into a website
are you that man?
Indeed @ornate crest
you'll probably have better luck with Selenium or something.
also you're almost definitely not allowed to be doing that so we won't help you with it. your school will probably have some terms somewhere that say "don't automate your user account". if they wanted you to do that, they'd have an API.
🤔 hm ok boss. thanks anyways.
Could I get a code review? Its my first Python project and still a major wip. https://github.com/radxix/irx
Ok! 😃
im trying to learn more python, and decided to mess around with flask backend with react frontend, but im having issues deploying it to heroku, anyone have experience with this?
Question on MVC. Should I put all my classes in model.py?? E.g. putting my calculator class that calculate things?
if i would like help with beautifulsoup, would this be where i ask?
@meager anchor coli am using flask. I plan to initialize these classes in the controller so I can do something like class.calculate
Does anyone have a resource for actual python + web development beyond the basics?
I've followed through with the Django tutorial on Django and it's way over my head. Most learning tools are all the basics.
Like...how do you take python code and turn it into a function website?
functional*
Currently going through Corey Schafer's flask tutorial on YouTube, give that a shot?
IMHO, it's trial and error until you stumble upon the resource that's right for you. But don't be disgruntled each time you stumble upon the wrong resource, you'll still learn something, no matter how miniscule. It'll be helpful somewhere along the way. Love the process, not the outcome.
There's also the djangogirls tutorial
class QuizCreate(CreateView):
model = Quiz
form_class = QuizForm
template_name = 'quiz/quiz_create.html'
success_url = reverse_lazy('quiz-page', args=[model.id])
how should I pass model id? this is giving me ValueError
(this is in django)
For a scenario where I am taking a lots of files from various users for other users to download, is this -
POST file to API
Save to server and respond to user
check for vulnarability (IDK how this works)
compress (base project)
send to amazon S3
return when users requires it
a good way to go about it??
No.
I did that and now I need to undo it.
You want the following type of thing
-
Client requests a "Save Location" form the API. The API gives it access to a specific location on an S3 bucket.
This is Write-Only access with no access to read on that location. -
Client dumps the file to the location.
-
Client tells the API that the file has been dumped.
-
The API then retrieves the file and processes it.
UIDs are your friend. Create a UID directory where the client can save the file.
About how to check for vulnerabilities: Do NOT re-invent the wheel. Either pay for a service or get some well supported regularly updated libraries / packages to do the job.
Once processed, add it to the Index (users listing the container can then see the resource)
The idea is to have an incoming only bucket for this workflow. The file needs to eventually end up on a CDN or something like that.
Note: The API creates a unique directory for every single request to upload a file!!! Once the file has been processed, delete the directory and file.
Also the file is not editable or deletable or overwritable by the client. Basically it is "write once"
Ping @twin thunder
Hey, thanks.. I've just started with boto from aws.. I'll have to see how this whole process is done. Like asking for a space.. As for the access, is it supposed to be done from the IAM?
Oh, forgot that this channel is for html, css, etc support.. dope
Love this server
Do the icons + text look centered to you? :/
well if i do this its not for sure...
I've found CSS Grid to be really helpful in cases like this.. Or Bootstrap Grid if you are using it.
I'll read this https://www.w3schools.com/css/css_grid.asp then 😃
How do I store extra data along with my file in AWS S3?
<section class="boxes">
<div class="grid-container">
<div class="item1">
<img src="./imgs/support.svg" alt="">
<h3>Lorem Ipsum</h3>
<p>Lorem ipsum dolor sit amet</p>
</div>
<div class="item2">
<img src="./imgs/support.svg" alt="">
<h3>Xorem Ipsum</h3>
<p>Xorem ipsum dolor sit amet</p>
</div>
<div class="item3">
<img src="./imgs/support.svg" alt="">
<h3>Yorem Ipsum</h3>
<p>Xorem ipsum dolor sit amet</p>
</div>
</div>
</section>```
```CSS
.boxes {
margin-top: 20px;
padding: 0;
}
.boxes {
text-align: center;
}
.boxes img {
width: 85px;
}
/* Grid */
.grid-container {
display: grid;
}
.item1 {
grid-column-start: 1;
grid-column-end: 1;
}
.item2 {
grid-column-start: 2;
grid-column-end: 2;
}
.item3 {
grid-column-start: 3;
grid-column-end: 3;
}```
I can't figure out why the distance between each item is so great: https://i.imgur.com/xYLZpEw.png
Any clues?
Huh 🤔
What's that?
What am I using then?
Let's say, you add grid-template-columns: repeat(3, 1fr) to your grid container
And grid-template-rows: 1fr 1fr for 2 rows
1fr is 1 fraction of height
ie 1 fraction of whatever space is available..
Oh and remove .itemX?
You can do that, it would be better
Cheers
But there is another property
Seems padding is the spacing issue https://i.imgur.com/tsH6LSj.png
Which I can't remember and am. Not on the laptop..
It is because you haven't declared the sizes of your rows and columns
Ooh.. grid-auto-flow: columns to your grid container.. YeH
I really wouldn't recommend w3's tutorials for this.. They are really misleading
Haven't seen grey before, assuming it's not
*dark grey
*Atom
Yeah dark grey = invalid
Yeah.. Just comment it out for now and try whatever is there.
Sweet same as before but less lines and don't have to declare for each item
Now all I need is to figure out this spacing/distance between items/columns
Yeah.. Now you can just add new items and if they are inside the container, they'll automatically go to their positions
Also, do use justify-items: center; align-itsems: center
*items
justify-items: center;
justify-items: invalid
justify-content:
I think that's what you're after
Yeah.. But before you jump into it.. I'd recommend you at least go and read the grid areas and the auto-fit auto-fill
Yeah.. I guess, I don't have my lappy rn and am a bit rusty on this.
No worries 😅 ❤
😄
https://gridbyexample.com/examples/
This is probably the best guide to start..
https://css-tricks.com/snippets/css/complete-guide-grid/
This is a good guide too
Alright reading about auto-fit and minmax but no idea what minmax to have 😅
And thanks
Don't jump to complex topics directly, you'll make too many mistakes to go back and correct..
Try using basic things.. Will help you in the long run..
Np man..
Will do 😃
Gonna try to solve this padding (column width) now 😃
grid-template-columns 😃
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: 1fr 1fr;
justify-content: center;
align-items: center;
grid-template-columns: 400px 400px 400px;```
Feels wrong though..
- I'm using
grid-template-columnstwice:
grid-template-columns: repeat(3, 1fr);
grid-template-columns: 400px 400px 400px;```
2. I have to specify each column by itself:
`grid-template-columns: 400px 400px 400px;`
Doing something wrong
Yeah knew it, could remove grid-template-columns: repeat(3, 1fr);
Eh still feels wrong, maybe it's not 🤔
Ok no, grid-template-columns: 400px 400px 400px; isn't working correctly. Weird stuff.
Using grid-template-columns: repeat(3, 1fr); but still have not figured out how to change the horizontal spacing between items/columns
You can replace 1fr with 400px if you want
Both lines will override each other
1fr is just measure of space
@autumn flare
Fr vh vw px em rem are all size quantifiers
Like.. They use Kg in my country to measure weigh but they use lbs or pounds in other places..
Also, the repeat(x, y) method just does what it says, it repeats a y sized row/col x times. ie you can write 400px 400px 400px or write repeat(3, 400px)
So, in Flask, I have a template called "status.html" in "templates". However, render_template raises a templatenotfound error
Is the templates folder in your project folder that contains your main app file?
!t ask
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving
• Keep your patience while we're helping you.
You can find a much more detailed explanation on our website.
hey guys, i am going through python crash course and going through teh django project first, i was following it closely but now i have over a dozen duplicates of admin.py, attached ^. Any idea on how this happened? Not sure which ones to delete and keep..
and i believe it's messing with my ability to add new apps to my admin page since i am not entirely sure which is the correct admin.py file to add Topic
did you create the files?
that's macOS, right? i've been having similiar issues with file duplication recently but it usually appends a random number
What are the args and kwargs used for here? https://www.django-rest-framework.org/api-guide/generic-views/#listmodelmixin
Django, API, REST, Generic views
i am not sure. I personally didnt create any admin.py files, the guess is that i may have hit manage.py in too many places
interesting, thanks for sharing
I know this is a python server but this is the best place I know to put it
Does anyone know how to use HTML forms and the submit button uses discord web hooks to send the form results to discord?
Pls @ me with responses
Hi all. I have a rest framewrok app where I've done a lot of work with viewsets and routers. I'm looking to make a custom endpoint that just returns a flat json response with some calculated fields from multiple different models. Anyone know of a resource I can use to browse? Going through the docs and I guess I'm not thinking of it correctly or whatnot.
hi
does anybody know how to call a python function when onchange
onchange=funciton()
but not js
if you are answering my question
please tag me
@teal scroll that's not really a thing. clients don't have python installed, they have js. the closest you'll get is to use a transpiler like Transcrypt to turn your python into js.
@rare oar sorry I need more details to give you any help with that. is your rest framework a python one? making an endpoint that returns flat json should be pretty straight forward, in that case, but we'll need to know what framework you're using to help you with specifics. what have you tried so far? got any code to show us?
@kindred gate This shouldn't be that hard, but you'll need to write some JS. basically you need to use JS to make a POST request to a discord webhook URL with the correct json data.
start by making a sort of hello world - write a simple JS function that POSTs anything at all your webhook URL
then iterate on that by adding the form data to your json payload
is there a module for generating swagger file for your pyramid app etc ?
@deep cave would the best way to do this be jQuery.post() or is there an alternative method?
it's possible to use vanillajs for it, but personally I do kind of like using jquery for that sort of thing, yes.
okay thanks for your help!
some different approaches here
no probs, let us know how it goes!
Thanks - content works fine, just sending embeds are a bit iffy - always returning 400 errors with what I try
@deep cave I can't seem to get embeds working - every single time it returns 400 errors
show us an example payload?
asin the code?
as in what are you sending in your POST request
what's the payload
I'm sure the code works if the content POSTs are going through ok
$.ajax({
method: "post",
url: "WEBHOOK URL",
data: {embeds: [{
description: "hello",
title: "title",
}] },
success: function() {alert("SENT")},
error: function(error) {alert(error);console.log(error)}})```
still errors
can I see the error, as well?
"Cannot send an empty message"
so basically it's ignoring the embeds data
pretty much
okay, I'm thinking you need to set your content type to application/json
and that maybe you're currently sending it as multipart form data?
yes, that actually confirms my theory.
it does allow stringified json if you have a form data content type
but that's cool then. I guess you got it solved.
is there a better way than JSON.stringify
I don't see a problem with that if it works
Thanks so much for your help! :D
you're most welcome
Also - while ur here
is there any way of keeping the webhook private
so that noone else can see it / post to it
weeell. not really. the code is executed on the client, so it's going to be visible to the user.
you'd need to handle it in your backend if you want it to be private.
are you using a python framework for this website?
like flask?
no, pure HTML
well, that's where something like flask would come in
with flask in the picture, you could call the webhook from the python backend, and the user would never see any of that. you wouldn't need JS at all.
it's not super complicated, either
a simple flask app is just a single file
with only a handful of lines in it
you could probably have it up and running in a few hours.
Hey I'm trying to deploy a django app to Heroku. I'm having trouble in deploying staticfiles. When I use {% load static %} and {% static 'staticfile' %} it works in the production server. But in the dev server django throws an exception Invalid block tag on line 7: 'static'. Did you forget to register or load this tag?
This is my settings for static files:
STATIC_URL = '/staticfiles/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
i ran collectstatic
i have 'whitenoise.middleware.WhiteNoiseMiddleware' in middleware settings
if I use {% load staticfiles %} and {% staticfiles 'staticfile' %} it works on dev server but not on production server
Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.
your STATIC_ROOT and STATICFILES_DIRS don't match
you use the same concatenation to build the URL, but different directories
interesting. I tried changing it, but it wasnt working on heroku
ill try again
in your opinion should I use AWS instead of Heroku? I'm doing a lot of scraping with Scrapy and I dont know if Heroku will be the best choice
ugh my problem isnt with heroku. Django is not recognizing the {% load static %} tag
{% load static from staticfiles %} it doesnt load like this also although there is a static function inside staticfiles
https://www.b-list.org/weblog/2018/nov/20/core/
The Django team is considering to move away from the idea of a core team
Hey all. When I try to spin up the docker images of the main 'site' project for this discord, it works. When I run app.py for the site though I see this come through: pdrmq_1_d8841305e421 | ERROR: epmd error for host pdrmq: address (cannot connect to host/port) I have set RABBITMQ_HOST to be a different IP that pings out (this has worked in the past). Any ideas?
also fair to say that RETHINKDB_HOST was giving a similar error before I changed the IP and now this is the error coming. So I think the IP is correct.
epmd is the erlang port mapper daemon, nothing to do with redis
you set the rabbitmq_host variable on the site container, right?
well in my pycharm run configuration. Is there something I need to do with the container?
for docker-compose I am running windows. Installed the Community Edition and checked to Expose daemon on TCP. in console typed docker-compose up and built the images. grabbed the ips rethinkdb spat out and changed RETHINKDB_HOST and RABBITMQ_HOST to that ip. Updated host file
those two env vars live in my pycharm run configuration. I am just running app.py (is that correct?)
you set rabbitmq_host to the rethinkdb ip?
yes I set both rabbitmq_host and rethinkdb_host to the same ip
but those are different hosts
I have tried removing rabbitmq_host and I am with the same error
the epmd error only appears when I try to run the flask app.py
RETHINKDB_HOST set to the 10.0.75.2 ip which pings out.
hmm not sure. Easy way to tell on windows? I don't see anything listed in netstat
netstat -a to include listening ports
hmm didnt see any
also I just spun up docker-compose right now. I was assuming the error came from when I tried to run the site. It looks like it errors out after awhile on its own with that message above.
Proto Local Address Foreign Address State
TCP 0.0.0.0:135 DESKTOP-S3I9VME:0 LISTENING
TCP 0.0.0.0:445 DESKTOP-S3I9VME:0 LISTENING
TCP 0.0.0.0:2179 DESKTOP-S3I9VME:0 LISTENING
TCP 0.0.0.0:5040 DESKTOP-S3I9VME:0 LISTENING
TCP 0.0.0.0:5432 DESKTOP-S3I9VME:0 LISTENING
TCP 0.0.0.0:7680 DESKTOP-S3I9VME:0 LISTENING
TCP 0.0.0.0:49664 DESKTOP-S3I9VME:0 LISTENING
TCP 0.0.0.0:49665 DESKTOP-S3I9VME:0 LISTENING
TCP 0.0.0.0:49666 DESKTOP-S3I9VME:0 LISTENING
TCP 0.0.0.0:49667 DESKTOP-S3I9VME:0 LISTENING
TCP 0.0.0.0:49668 DESKTOP-S3I9VME:0 LISTENING
TCP 0.0.0.0:49669 DESKTOP-S3I9VME:0 LISTENING
TCP 0.0.0.0:49670 DESKTOP-S3I9VME:0 LISTENING
TCP 0.0.0.0:49708 DESKTOP-S3I9VME:0 LISTENING
TCP 0.0.0.0:54235 DESKTOP-S3I9VME:0 LISTENING
TCP 0.0.0.0:54236 DESKTOP-S3I9VME:0 LISTENING
TCP 10.0.75.1:139 DESKTOP-S3I9VME:0 LISTENING
TCP 127.0.0.1:2375 DESKTOP-S3I9VME:0 LISTENING
TCP 127.0.0.1:6463 DESKTOP-S3I9VME:0 LISTENING
TCP 192.168.1.16:139 DESKTOP-S3I9VME:0 LISTENING
That is what is listening right now. I thought 5432 could be it so I tried changing the port to that but no dice
@deep cave Hey sorry didn't see the reply. I am using django rest framework. I'm just a bit new to it and have only used the magic ModelViewSet. If I was to do a regular viewset, would I just provide a Response that sends a dictionary instead of someserializer.data?
Hi, I'm quite new to web development, but how hard would to be to authorise with discord and make a bot web panel? All it'd be is a set of buttons that interact with a database (postgres) using preset queries per each button.
I was thinking of using django and having a fairly barebones (no css for now) webpage for it, where you'd select a server to change settings on, then it'd change columns with that server's id.
Sorry if it's a stupid question ;;
Is Quart a good web framework for making sort of advanced websites?
@rare oar I'm afraid I'm not that knowledgable within DRF, but maybe @meager anchor can help you.
@nimble crow it's not super complicated. we've done something like that for our website, although that's for Flask. You can look at https://github.com/python-discord/site/blob/master/pysite/oauth.py if you want to see some of the code we're using for it.
it's definitely doable
@elfin trench in my opinion you're making it harder on yourself than it needs to be if you're using Quart for an advanced website, I'd stick with more established frameworks like Flask or Django unless optimal performance is absolutely paramount. it's hard to say without knowing more about what you mean by an advanced website.
I'm using this for my upcoming discord bot. It's gonna contain a API of user info/leaderboards, a dashboard, and a admin dashboard of statistics and such
uh
sry I accidently deleted
sorry lol
Wrong lemon... Again
you're putting the API directly in the bot?
because that's geeenerally a bad idea. it gets really messy.
it's generally just a better idea to keep the two apps separate and have them communicate.
no on the website lol
hey @elfin trench I've done the same on my discord bot. If you run into any questions shoot me a pm. I've uhhh... learned quite a bit not knowing anything about restapi etc. Web end is a django app with Django Rest Framework. Bot uses discord rewrite
@deep cave I got it figured out. Thanks 😃 😃
I though of using Flask
yeah flask is definitely a use case
especially if its only an api. I wanted to flush mine out to be a full on webpage later on and just have the bot act as a client for management in discord (its for game organizing and stat tracking)
well
It was going to be a dashboard
and a admin dashboard for statistics
and a API
ok. whatever you are comfortable with. I still think Flask is an ok choice. I chose Django because I had done a tutorial or so in the past
and kind of understood it better
easy choice then 😃
for the bot, not sure if it was the right way, but I went with a mixin that I put on my COG class that gives it access to the web api
at first I tried data classes, but man... I was getting a lot of naming and recursive import issues because my cogs weren't loosley coupled
so I went with that route instead
I'm thinking of using aiohttp or something
to communicate
or sockets idk
I'm just unsure of what I'm gonna do when communicating cause I haven't learned those stuff yet lol
I use aiohttp
The thing is I'm not sure of how I can get information from the bot to my web app. Like how would I tell my bot to send that information lol
what do you mean?
I think it would be like any POST call
I need to refactor this as this is a method not in my mixin now, but heres the gist of what I do:
async def api_base_method(method: str,
endpoint: str,
resource_id = "",
session=None,
**kwargs) -> aiohttp.ClientResponse:
"""Generic function that takes a method for a web api call.
Valid are GET/PUT/POST
endpoint is the full url path.
"""
url = endpoint if resource_id == "" else f"{endpoint}{resource_id}/"
log.info(f"Calling api_method: {method} on {url}. ")
for key in kwargs:
if key == 'json' or key == 'data':
log.info(f"api_method {key.upper()}: {kwargs.get(key)}")
auth_token = os.environ.get('API_AUTH_TOKEN', None)
auth_header = {'Authorization': f'Token {auth_token}'} if auth_token else None
if not session:
session = aiohttp.ClientSession(headers=auth_header)
response = await session.__getattribute__(method)(url, **kwargs)
response_status = response.status
response_text = await response.text()
await session.close()
else:
response = await session.__getattribute__(method)(url, **kwargs)
response_status = response.status
response_text = await response.text()
log.info(f"api_method {method} returns {response_status} - "
f"{response_text}")
return response_status, response_text
async def get_record(self, endpoint: str, id: int, **kwargs):
"""Returns a web api object from our database.
:param endpoint The endpoint to target. ex: `match/`
:param id The pk of the object from our web api.
:return dict A dict representation of the object.
"""
endpoint = f"{self.api_root}{endpoint}/"
status, record = await api_base_method(method='get',
endpoint=endpoint,
resource_id=id,
**kwargs)
if status == 200:
return json.loads(record)
I also have a save() method which does a post.... but its a bit long and really needs refactoring
heres a command from the bot:
@events_group.command(name='checkout', aliases=('co',))
async def events_checkout(self, ctx: Context, event: EventAPIObject) -> dict:
site_member = await self.get_record('discordplayer', ctx.author.id)
log.debug(event)
event['players_checked_in'] = utils.remove_dict_from_list(site_member, event['players_checked_in'])
await self.api_save('event', event)
await ctx.send(f"Succesfully Checked out {ctx.author.name} from Event {event['id']}")
POST methods send information right?
yeah POST is for creating something in the database
hey
https://images-ext-2.discordapp.net/external/AEeWmdByIyBjIC8OvtsXhtktOouf8Xh8qo7LJZXeAK4/https/cdn.discordapp.com/attachments/377162169697173505/508661738179264541/jon_snow_landing.png?width=649&height=487
How can I achieve something like this?
Like the background behind everything.
What I mean is, how to get a background image positioned where I want?
Lol, idrk how to explain what I'm thinking.
Depends on whether you're going hardcode and do all of this yourself in html or css, or if you use a framework.
What framework could I use, if I was? @still briar
If it's just about styling, I'd use Bootstrap.
Hm 🤔 . But would it be quite difficult if im going hardcode?
Depends on what you're aiming at. If you're mostly interested in the structure, such as having the big text top left, then body text to the right, that needs some proper layouting.
But if you want to make it just as pretty, there's a lot you'd have to add, I suppose.
You can look at the internals of the page to see what they are using
@quiet solstice That's a design which I found on dribbble. Do you know any other websites which do something similar.
I do not, I wonder if it's even one thing or if these are separate
I always thought it was separate.
I am Jon Snow
Important attributes of my skills
"knows nothing"
sorry lol couldnt resist
something like this?
height: 100%;
}
.bg {
background-image: url("https://mdbootstrap.com/img/Photos/Horizontal/Nature/full page/img(20).jpg");
height: 100%;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}```
bg would be the first div in your body
that too
looks like w3 does it the same way >.<
Any good NLP libs out there for rephrasing search queries?
Preferably python or JS
the error is straightforward. Foreignkey is not a thing, it's ForeignKey
Small letter k? @meager anchor
then you must have more than one instance of Foreignkey that need to be replaced
¯_(ツ)_/¯
Hey how can I render django form fields manually. I'm storing the field on creation in a dict. When I loop on this dict the field is rendered as repr. The label shows ok but not the field. It shows like: <django.forms.fields.FloatField object at 0x000001DC71FFEC50>
@high star cant get u sir im sorry can u comment in the code please as a noob i wanna learn
@raven harbor did u run migrations again?
ctrl-f in your file shows two Foreignkey references
after changing Foreignkey to ForeignKey
if you changed one but not both, you'll still get the same error
@grand badge s I did . Ended up with same error
Done yeah there are two foreign key
What is the best cheapest hosting service for Flask?
AWS Lamdba/API Gateway using zappa @wary mantle
Nothing will beat a carefully crafted serverless deployment for cost.
Django beginner, here
if I had a model "PImage" with a field "img" which an image field (as below:)
#from models.py
class PImage(models.Model):
img = models.ImageField(upload_to='photog', default="")
title = models.CharField(max_length=140, default="Title")
date = models.DateField(("Date"), default=datetime.date.today)
def __str__(self):
return self.title
How do I get it to save objects to a listview? It works with a different model but not this one.
Example:
# views.py
class PostList(ListView): #works fine
model = Post
context_object_name = 'posts'
class ImageListView(ListView): # doesn't work
model = PImage
context_object_name = "ilist"
hi people... I am working on a django project which uses the new Facebook API to fetch instagram user data.
does anyone here has any experience in this are? It would be a real big help for me.
Is there a way to update a file inside a lambda function periodically?
sounds like a thing to not do. why does it have to be a lambda
if lambda means AWS lambda, the question would be we it should not be a lambda? one of the use cases of it is actually replacing crondemon
hey
what do you think of this course?
is it pretty good all-around course
from 0 to deployment?
hey guys, I know you can display html in jinja2 by using {% include (filename) %}, and the base functionality is fine for me
but the html file I include links to a local stylesheet that it no longer renders upon being included
any tips? Couldn't find anything on Stack Overflow
can you show us your templates?
So right now it's correctly displaying all the html files, but not using the css in those html files
free udemy courses for flask
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving
• Keep your patience while we're helping you.
You can find a much more detailed explanation on our website.
I have absolutely no idea what to do for Django. I did the tutorial that they have provided, and i'm trying to get my own program running, but idk how it works or anything
im using a library that i created to make a program
if needed, i can link the library code here
i haven't done anything in Django regarding my program yet, except for creating the project.
idk much about django but ik Corey Schafer has a video on it making a blog
pt 1 - https://www.youtube.com/watch?v=UmljXZIypDc
In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic app...
if that helps at all
mk you can still follow it tho
i did
it shows how to make pages
like i said, i did the first part of the Django tutorial already
but i'll check the video out
thanks!
np
Is there a Django application for searching using class based generic Views?
Does anyone have a codebase out there that builds a large flask api without using flask-restful? I'm experiencing some architecture concerns and I'd like to understand how the app connects to its endpoints.
i need to use stripe to receive payment and process order just for test purpose for my final year project . to get api key i need to provide website link and bank details . but my project is not in realtime how can i use stripe in this case...
hi chaps got a question!
#route to page
@app.route("/role_managment")
def role_managment():
newRoles = ExtendedAddNewRolesManagmentForm()
return render_template('views/manage/management_role.html', form1=newRoles )
#post method
@app.route("/form", methods=['POST'])
@login_required
def form():
value = ExtendedAddNewRolesManagmentForm(request.form)
if value is None:
flash('nothing entered')
return redirect(url_for('role_managment'))
print(value)
role = Role(name=value.role.data)
db.session.add(role)
db.session.commit()
flash('Completed')
return redirect(url_for('role_managment'))
#this is the form:
class ExtendedAddNewRolesManagmentForm(FlaskForm):
role = StringField(label='Role Name')
exist = SelectMultipleField('current', choices=RolesList.role())
submit = SubmitField('submit')
def role():
b = []
conn = Role.query.all()
for item in conn:
b.append((item, item.name))
print(b)
return b
im trying to return all my role names to a tuple and show then in SelectMultipleField but keep getting an error
which is ``` undefined field ````
Paste the full traceback if you still need help
ah is this where the django ppl are at
Hey!
Using Flask, I'm trying to:
- Click a "Test pump" button.
- Call a "pump_water.py" script on the server.
- Update the HTML with a "Pumping..." text.
- When finished, set that text to "Test pump"
But I can't get it to update both after and before the pump is done.
My flask code atm:
def pump():
pump = Popen(["python3","/home/pi/Circuits/Pump/ttest.py"] )
data_template = template_creator({"pump_info":"Pumping..."})
print(data_template)
#UPDATE HTML HERE
yield render_template('index.html', **data_template)
while pump.poll() == None:
print("Inside!")
time.sleep(0.5)
#UPDATE HTML HERE
return render_template('index.html', **template_creator())
return render_template('cakes.html')
Note: the yield obviously causes an error with returning a generator, it's just there to show where I want to return.
Any and all assistance appreciated!
Ping me if you know
hi ummm was wondering if anyone can help my small flask issue
def index_post():
text = request.form['text']
brand = text.upper()
with open("Vehicles.csv", "r") as vehicleFile:
vehiclefilereader = csv.reader(vehicleFile)
data = ""
for row in vehiclefilereader:
vehicle_id, make, short_model, long_model, trim, derivative, year, discontinued, available = row
for field in row:
if field == brand:
data = f"Model: {long_model}\nDerivative: {derivative}\n"
print(data)
return render_template('home.html', brand=data'''
kinda new here so was wondering how the stuff in my if i can pass to my template?
basically after looking though the csv n printing the results passing that data into the template text area
?
May be a bit. These channels are less frequented but the folks who reside here are quite knowledgeable
def index_post():
text = request.form['text']
brand = text.upper()
with open("Vehicles.csv", "r") as vehicleFile:
vehiclefilereader = csv.reader(vehicleFile)
build = list(vehiclefilereader)
for row in vehiclefilereader:
vehicle_id, make, short_model, long_model, trim, derivative, year, discontinued, available = row
for field in row:
if field == brand:
data = f"Model: {long_model}\nDerivative: {derivative}\n"
build = data
return render_template('home.html', brand=build)```
small update got it to print out all contents of csv but just now only want to use the build inside the if
hi all. is it possible to use
<input type="datetime-local">
and format the date to be YYYY-MM-DD HH:mm?
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local
@grand badge yes, I mean something that will allow me to search through models I have in the database and display the relevant ones on a page
like a catalogue search for library books for instance
all of the tutorials I am finding for it are for function-based views, but I am using class-based views
@brittle glacier you need to make javascript on the client poll the server, you cant just spit out more html on the same page
start the process with this call. then create another page/route that you can query for its current status. use javascript to make the browser keep checking that other page
@opal leaf Do I need Ajax to do this?
youll need something like that yes @brittle glacier
hmm alright
I'm not too good with Ajax, do you got an example of how I could do what I*m trying to do?
sorry i am not either, i just know you need to
the flask docs have a page on it though http://flask.pocoo.org/docs/1.0/patterns/jquery/
Dope!
The only Flask integration I've seen so far is using a-elements to href functions in flask
I'm very new to Web Development. Can someone help me understand where to start? plz and thx!
@verbal cobalt Start with HTML css and JavaScript. Then learn python(flask) and MySQL
There are many other paths though
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}!')
return redirect('blog-home')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
anyone know why ?
nvm
problem in profile creating
Hi
Does flask support concurrent requests?
(As I understand, it does not)
Can someone please point me to some place where I can understand about gunicorn + nginx
and what exactly is the use of them with flask.
Thank you
@dusk junco If you are overriding save() on a model or anything, make sure to pass in *args and **kwargs
I'm trying to download a file from my server. In my Flask API, I use:
send_file(path, mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", attachment_filename="test-server.xlsx", as_attachment=True)
But I don't know how to process it from the client side. I am afraid the data sent is on a wrong format.
When I try:
new Blob([response.data])
the blob size is wrong (too small like 2)
Any tips or suggestion?
I'm stuck on that for days
Is Flask side fine?
hello guys. im plannig to learn html and css and i have found several playlists on youtube.
https://www.youtube.com/playlist?list=PLB5jA40tNf3vh75MBwUb4oqiXFOZ5pYyX
https://www.youtube.com/playlist?list=PL4cUxeGkcC9ibZ2TSBaGGNrgh4ZgYE6Cc
https://www.youtube.com/playlist?list=PLgGbWId6zgaWZkPFI4Sc9QXDmmOWa1v5F
https://www.youtube.com/playlist?list=PLS1QulWo1RIbPrLaiosApdbbTwk-xMlIa
These are the playlists i have found. I wanted to ask, if any of u guys watched any of these, which one would u recommend? Or it doesnt have to be from these playlists, its okay if u can recommend other sources. Thanks in advance
If you're new to web design / development & don't know where to start, HTML is the perfect place. HTML and CSS together form the building blocks with which t...
Even if your goal is not to become a web designer, learning HTML and CSS can be an amazing tool to have in your skill-set – both in the workplace, and at hom...
@oak niche i recommend mozilla developer network's docs which are very cool and easy to understand just go to html section and go through every subsection of it, and you are good to go.
they have written those docs as tutorials , which means they are not exausting.
and here is the link:
you can also learn css and other web stuff from there
thank you so much! so it would be better to read when it comes to learning for u?
i mean compared to learning thorugh videos, which is better?
video tutorials are also great but they left you in middle of the road with half knowledge
alright thanks again
do you like videos, when it comes to learning
i have been into programming for like 6-7 months, and i have learned almost everything through videos untill now
i have studied c#/sql, and the past 3 months, i ahve been learning python
since i learned basics, im plannig to jump into web development with flask/django
then this tutorial series on html is great for you
and when it comes to css i recommend frontend masters' css in depth course
which is great and it teaches specifity in in-depth
thank you so much, ill start as soon as possible!
and i must recommend a video series on django :
enjoy learning
Hello! any recommendations for client for a machine that can respond to a flask socketio, I tried to understand the unofficial library of socketio client python but it doesnt seem to clear
Im looking for some way to respond that doesnt involve opening up the browser
@native tide You can make a searchbar with class based views
You will need to make use of the get_queryset() method
example
where it says self.request.GET.get('term') it gets the data from the form named term
you can of course name the form anything you like
the second last line filters out any posts that are not matched with the search query and only holds posts that are relevant to the query
You'll need to add something like this to your templates
inside the form, you would make a {% url %} inside the action attribute that links to the url you specified for your class
In addition, you would set the method attribute to GET
In this line
<input class="form-control mr-sm-2" type="text" placeholder="Search posts" aria-label="Search" name="term">
The name attribute is set to term. It can be anything you like but it must match the name you put in your view's code. This is how the data from the form is collected.
Anyone here mind helping me out with setting up things as http://flask.pocoo.org/docs/1.0/patterns/packages/ suggests?
I have a file called config.py, and it looks as follows:
from PasteMate import flask_app
from flask_cors import CORS
flask_app.config.update(
SQLALCHEMY_DATABASE_URI="sqlite:///PM.db",
SQLALCHEMY_TRACK_MODIFICATIONS=False,
SECURITY_PASSWORD_SALT="12345",
SECRET_KEY="12345",
CORS_SUPPORTS_CREDENTIALS=True,
JWT_SECRET_KEY="12345",
JWT_BLACKLIST_ENABLED=True,
JWT_BLACKLIST_TOKEN_CHECKS=['access', 'refresh'],
JWT_COOKIE_CSRF_PROTECT=True,
JWT_COOKIE_SECURE=False,
DEBUG=True
)
and in the module containingflask_app,
from flask import Flask
flask_app = Flask(__name__, template_folder="../client/")
import PasteMate.app.config
if __name__ == '__main__':
print(flask_app.config)
flask_app.run(host='localhost')
The config doesn't get updated
and yes those security options are horrible
hi people, i wanted to start working with API using django, any recommendation where i should look at? :3
When building an API what do you call that folder that you build the routes in?
Bro, start with the Docs.
@raw nexus the tutorial on the Docs is pretty good
And then there's a lot of good YouTube videos about getting started.
Can you give me the link of the official docs? :3 i seems can't find it
is it possible to make a fairly basic web game in Django/Python? and how difficult would that be
but multiplayer, but not necessarily real time
Thanks ^^
You could make a web game fairly easily with Django. You'd have to use channels to do something more in real time.
Any here..?
I wanna make stock management system using python with django. As a noob I don't know where to start this is first time I'm working with database on python can anyone send me any guide or video related this.. please.@everyone
Do you think that justifies trying to mention over 10,000 people? 
Sorry but I have no other idea @olive wharf
imagine the everyone ping wasnt disabled lmao
Can anyone help me with that
its sort of a broad question imo
you say you have never worked with databases
@raven harbor https://www.youtube.com/watch?v=r9kT-jm136Q
In Django, or any web framework, models to interact with your databases are extremely important. In this video I show you how to connect to a database, creat...
Thanks a lot that will be a good start for me
my gosh. I am convinced I approached my models wrong. Every instance is a battle against the number of queries generated. I put in a simple jinja2 view and I'm generated 3000 queries on the relationships
I don't understand. In Django if I do MyObject.somerelation_set.all() it just explodes. Its such nice nice magic, but it murders performance
if anyone is available, can they help me digest it? I'm sure its just my understanding of how to query it
Thanks @grand badge that helps me a lot
But a similar question about searching in django; I can send queries using the form element, but how would I send a query using a link? For instance, if I have a word that acts as a tag and if a user clicks on it, I want it to go to the search page with the word entered as the query.
Heyo
So I'm going to make a temporary file hosting site with Flask.
It's going to have expiration options, so I'm wondering what I can do when a file expires as someone is downloading it?
Are there any Bottle, CherryPy, Falcon, Pyramid, Responder, or Sanic devs in here?
@lilac hound that shouldn’t matter, the file will be locked while it’s being read, and then once it’s in memory and streaming to the user it will be free for deletion
@full arch I should say this though
I'm going to be storing the files (max 50mb) in a database, since I want to password protect and encrypt them
So when a file expires I just will remove it from the database
But I kind of figured it would be that way though in regards to it being read
Same thing, you won’t be streaming directly from the database. But you really shouldn’t use a database for file storage, it’ll destroy performance
Well, what's another way of doing this?
I just want the files to be secure, encrypted, and passworded.
A database seemed like the best option since I could just have two datefields, submitted and expires, to run a cron job against
@floral dust I've used cherrypy a lot and I've contributed to development. What do you need to know?
@paper raptor I have been working on a security headers / cookie project and would love some feedback - https://github.com/cakinney/secure
I'll take a look at it. Its a lot to go through, but could save much time.
Part of why i love cherrypy is that it doesn't do much and doesn't get in the way, but the downside is having to do a lot of stuff manually that could be done much easier, like this.
Thanks! I would really appreciate any suggestions - I know it has a lot of moving parts
Agreed! I wanted to create it for those micro-frameworks without this support built in. I am more security engineer than developer so this is my way of giving back.
@lilac hound a database isn’t inherently more secure than file storage. You would need authentication for either if you wish for secure access.
I would recommend a database to store your file meta-data (age, creator, etc) and a path/uri to the file.
@full arch I am just not sure about encryption/decryption with that
Have any libraries you can suggest for that?
Quick google got me that, @lilac hound
That flask plugin isn’t currently maintained by the looks of it, but the library it uses is still active https://github.com/andrewcooke/simple-crypt
For authentication/administration , I’d recommend https://github.com/flask-admin/flask-admin
If you don’t need an admin dashboard, https://github.com/mattupstate/flask-security
How much RAM would a small Flask server and a few web pages take up? (if that's measurable by RAM?)
i guess it depends
< 100 mb
What would be the best way to implement Flask into my website?
I don't want it to "load a new page", which I've seen iterations do. I just want it to do some python functions.
For the love of God, I can't figure out why my site sometimes loads, & sometimes why it directs me to DNS search, as if it doesn't exist
Its acting like I'm using the Flask development server (but I'm not), I'm running Flask/uwsgi/Nginx
Anyone know of any reason why this would be happening, in general?
What weird error would be causing the site to work only half the time
So has anybody here really touched Flask?
I have!
@brittle glacier ... Little late, soz. But yeah, big fan. I'm deploying a flask app to production for my school where I work this week.
@prime ridge Awesome to hear! Do you have any clue why I keep getting "Method not allowed" when I call this with jquery?
:O
Never seen templating used in javascript before. Usually serve them as static files. I take it that javascript isn't being served as statically despite it containing template code, right?
you might want to add a print(request.method) to your view and see what's happening when you get that message
Also, I don't think methods are case sensitive, butttt
nah that's dumb
but in some code I'd written previously I had <form method="POST" action="/admin/"> allcapz
oh gosh
When I do "method=POST" in the form, that is when I get the "Method ot allowed"
never any other time
Wanna see if you're able to do it?
Yeah, sure!
HTML form -> jquery -> flask
It should be a JSON file in Flask
It's almost 8am here and I haven't slept. Let me know if you find something!
Oh, gosh
thought you were gonna throw me some code, haha. I'm about to sleep too
But HMU later if you wanna toy with it. 2 AM est here. I'll be on, like, 5 PM est
good luck!
For sure! Feel free to DM it to me, ideally.
Hello.
Being unsure to which channel to post to, web development seems to be the closest one.
What I'm trying to do is to get the data from https://www.portal.reinvent.awsevents.com/connect/search.ww in text format. Looks like it was done before, but with using browser emulation: https://github.com/mda590/reinvent_schedule_extract.
I'm trying to put up a plain python script without browser emulation.
I have tried to send few requests and figured out that first POST to get the data is sent like so:
data={
'searchType': "session",
'sortBy': "abbreviationSort",
},
All subsequent requests look like this:
data={
'searchType': "session",
'more': "true",
},
Somehow server knows what data to send with this "more" request and I was unable to figure out where does it take the data from. There is no such thing as "page" or "offset" in the request. Cookies do not seem to contain any kind of "what data is loaded last" hints, neither does the local storage. Same goes for POST request urls, they are always the same.
Essentially, the question is - where and how does the server get the info, based on which it decides which piece of data to load next? Function names, requests and other hints suggest site uses http://directwebremoting.org/dwr/index.html to serve this page. I'm unsure where to dig further.
Any advice, please?
Thanks.
hello guys I am using tornado
and I want to do some super heavy processing after a user has uploaded a zip of images
this processing will take a long time so I think I should run it in a new thread
or should i just hold the http request
the heavy processing is on a gpu
Depends on what response you need to send to the user
Then i'd run it in a new thread and just send a confirmation response back to the user
that is how I have currently written it
that way your connection isn't taken out of the connection threadpool for ages
and the client won't timeout
@brittle glacier can you give more info on the stack trace? is that occurring on the client side? In the browser?
could it be a possible CORS issue ?
I'll post all code in a few mins
@native tide @prime ridge
HTML: https://hastebin.com/xaxufasoba.xml
Flask: https://hastebin.com/cologurila.py
ohi
ohi ohi
snackin'
what what?
cheetos
loloo
Gotta be honest I don't have a ton of time to spend setting this up tonight. If you want to setup your issue using repl.it so I can actually just go in and tinker with the working code I'd be game
I tried but
So the goal is:
- html form
- jquery
- dict in Flask
you have some dependencies I couldn't find on pypy
or you didn't include all the files
The bottom one
isn't that, like, needed for one of the routes you're having issues with?
uhhh
One thing I noticed
you're not loading jquery at the end of your page
jquery should be loaded right before </body>
File "main.py", line 6, in <module>
from cron_handling import CronHandler
File "/home/runner/cron_handling.py", line 5, in <module>
from crontab import CronTab, CronSlices
ImportError: cannot import name 'CronSlices'``` dood idk what version of crontab you're using
Yeah, I gotta give up on trying to reproduce your environment. Feel free to upload your project to repl.it and I'll take a whack at it if you get it running there
@prime ridge tbh you can just remove the crontab stuff. I can handle all that as long as I get a dict into python
Noooooo. I don't wanna sift through and see what code is needed and what isn't.
I do that all day at work.. ;_;
I'll make a narrowed version in a sec! 😃
I'll try it.
Didn't mean to imply you should clean the code yourself, sorry for that!
Also, with that code only the form is usable, but that's the only thing that isn't working for me
ok got it
I mean
I didn't fix it
just, it's running
index.html is refreshing infinitely, why?
Yeah I had the same problem last night
Removing the evenDefault from jquery should fix it
No fucking clue why
Tried to make it stop refreshing but it just spammed refresh
Oh really
Lemme see
you mean EVENT default?
Top one
ok so
I see the problem immediately
and I kinda hinted at it last night
It redirects to /?Minute=fdsf&Hour=dsf&Daymonth=sdfsd&Month=dsfsd&Dayweek=dsfsdf -- you can't POST to that, because that's part of your index() route
it's not going to your result view
<p>Submit<input type = "submit" value = "submit" formmethod="POST" formaction="/result"/></p>```
That seems to be working fine.
lololo
@brittle glacier
although you may want to delete the second "submit" since it's a little... repetitive
altho wait is that even ajax
looks like it's actually just posting the data normal
@prime ridge So that works?
It works like a normal form
but it's not ajax
doesn't look like you have any ajax written
to go to /result
function formSubmit(){
form_data = cron_form.serialize();
var promise = $.ajax({
type: "POST",
url: "/result",
data: form_data,
timeout: 10000
});
}
oh derp
Bottom of tha ajax
at formSubmit (?Minute=&Hour=&Daymonth=&Month=&Dayweek=:194)
at HTMLFormElement.onsubmit (?Minute=&Hour=&Daymonth=&Month=&Dayweek=:86)```
at Vc (VM2358 jquery-latest.min.js:4)
at Vc (VM2358 jquery-latest.min.js:4)
at Vc (VM2358 jquery-latest.min.js:4)
at Vc (VM2358 jquery-latest.min.js:4)
at Vc (VM2358 jquery-latest.min.js:4)
at Vc (VM2358 jquery-latest.min.js:4)
at Vc (VM2358 jquery-latest.min.js:4)
at Vc (VM2358 jquery-latest.min.js:4)
at Vc (VM2358 jquery-latest.min.js:4)
at Vc (VM2358 jquery-latest.min.js:4)```
Infinite loop?
No idea why, haven't done anything special
closes infinitely refreshing browser and plays overwatch
I'll remember you in therapy
Most off those don't go through Ajax
Possibly all
Else I would've copy pasted lol
Is this work-related btw?
Christmas present related
Making an automatic plant waterer for my mother, controllable over the internet
D'aw
Where you gonna host it?
Also, I might recommend looking into tornado
it uses websockets and might make your life easier... or harder
Nice. Use supervisord or something to make sure it can handle failure
no clue what that is
but getting this damn thing to work is step uno \o/
i believe in you
I'd recommend "restarting" (don't freak out, you can copy and paste old code as it becomes relevant) and just focusing on getting a simple form working.
Why do you want the form to use ajax?
Wait I got a step further
cron_form.addEventListener("submit", function(event){
event.preventDefault();
cron_info.innerHTML = "mat";
formSubmit();
});
The innerHTML worked
and it does not refresh
:o
:o?
:ooo
Fuck if I know how it works
Shortened it to
cron_form.addEventListener("submit", function(event){
event.preventDefault();
var values = $(cron_form).serializeArray();
formSubmit(values);
});
Appearently the dollar signs are important
HA
wew!
nice
I'm designing a Flask Restful API and I am having a hell of a time trying to figure out how to do validation which also has the appropriate HTTP status code.
EG: Trying to view a resource from the API that has expired should return 404,
Attempting to sign in with invalid credentials returns 400, etc.
I've gotten by with doing credential validation and 400 codes with Flask-WTForms using the Flask-WTForms-Json extension, but I am beginning to lose the battle here.
I have had to do this:
class PastePermissionValidator: # TODO: Couldn't this be a WTForm validator?
def __init__(self, paste_uuid, username, data=None):
self.paste = Paste.find_by_uuid(paste_uuid)
self.user = Account.find_by_username(username)
self.data = data
def paste_exists(self):
return self.paste is not None
def validate(self, include_edit_perms=False):
if not self.paste_exists():
return {'errors': 'Paste with specified UUID not found.'}, 404
user_owns_paste = (self.user.id == self.paste.owner_id)
paste_requires_password = self.paste.password is not None
request_password = None if self.data is None or 'password' not in self.data else self.data['password']
if include_edit_perms and not user_owns_paste and not self.paste.open_edit:
return {'errors': 'You do not own this paste and open edit is not enabled for it.'}, 401
if paste_requires_password and not user_owns_paste:
if request_password is None:
return {'errors': 'Password is required.'}, 401
elif not self.paste.password_correct(request_password):
return {'errors': 'Password is incorrect.'}, 401
return None
Does anyone know of a good restful API validator library I can use to help me with this?
I'm honestly thinking of just rolling my own soon
how do i grab that in css? i tried .nav img { } didn't work
@dusk junco that looks like:
a.navbar-brand img.wanker {}
oh shit forgot to change the class name
lmao
anyway thanks
dont get me wrong im running out of ideas to name
Np, welcome. =]
anyone tried https://kbrsh.github.io/moon/ ?
The minimal & fast UI library.
also what do you use for page layouting - grid or flex?
@prime ridge What's the diff between "url for" and just typing the url?
Code?
Oh, in flask?
Sony remember off hand (going to bed) but there's functions to generate links to views without hard coding a url, which is good
And there's also code to do the same for static files, which is good
any javascript ppl here?
!t ask
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving
• Keep your patience while we're helping you.
You can find a much more detailed explanation on our website.
hey guys. i want to build a web scraper using bs4 and request. i stuck with a problem of "list index out of range".
should i post my (noobish) .py file here?
@wise fulcrum flex and grid serve different purposes
I use flexbox quite often, grid hardly ever - but that's my scenario
Try margin: auto for brand or it's image.
Greetings
I have a question. Is there any way I could check the TLS 1.0 and 1.1 is enabled on in my application or not? if it is, how can i disable it. so far I have tried adding something like this
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
context.options |= ssl.OP_NO_TLSv1
context.options |= ssl.OP_NO_TLSv1_1
sock=socket()
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
We don't permit recruitment in this server, we are a help server @modern acorn
anyone active here? i have some beginner questions here 😃
!t ask
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving
• Keep your patience while we're helping you.
You can find a much more detailed explanation on our website.
Where should I host my python app in order to use it online
i found an image from a website that i want to use i found the
url('/assets/images/bg/logo-image-masdar-en.png
is it possible to find the image and save it locally from this information?
the attribute*^^
here is a link: https://masdar.ae/en/masdar/our-story
it's the logo saying "masdar a mubadala company"
does any of you know how to get that image?
upper left side of the page. Would be much appreciated
/assets/images/bg/logo-image-masdar-en.png - prepend it with the protocol and website domain.
So that it looks like http://website.domain/assets/blah-blah.
But most of the time you can just right click it and save.
ahh it worked. thanks!
now when i used it as my background.. the font color black was no longer a good color.. how can i change all the fonts to white in this code:
% rebase(skinning + '_skin.tpl', title=page_title) # (See note above)
% # From here, concentrate on the content we would like to show:
<!-- Lines not starting with % are standard HTML. This HTML code is defined in views/all_items.tpl -->
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
% for k in displaykeys:
<th scope="col">{{k.title()}}</th>
% end # Usual python indention to structure code does not work in .tpl files - "end" is used instead to end a block
</tr>
</thead>
<tbody>
% for i, d in enumerate(displaydata): # displaydata is expected to be a list of dictionaries
% link_url = "/events/" + str(i + 1) # relative url to detailed view
<tr>
% for k in displaykeys: # Go thru the keys in the same order as for the headline row
<td>
<a href="{{link_url}}" alt="See details">{{displaydata[i][k]}}</a>
<!--numre-->
% print (i)
<!--category-->
% print (k)
</td>
% end # Usual python indention to structure code does not work in .tpl files - "end" is used instead to end a block
</tr>
% end
</tbody>
</table>
</div>
any idea @candid basalt ? sentence starting with "%" has some python code in it.
Changing font colors and such is a task for CSS.
In CSS you would do it something like this:
body {
color: white;
}
hmm but i dont think im doing any css here
yes but you have to if you want to do color stuff
ahh okay. What does it take to do that in general? like do i have to downloade something, make a new file or?
Make a new file and add a respective tag into your html template.
Does a pretty good job on explaining the basics.
wait. i just got the job done. Just inserted this line style="color: white;"
like this <h1 style="color: white;" >Testing font color</h1>
it worked. So is this what is meant by "using CSS" or was this just an html solution i just found?
@candid basalt when i inserted the logo that u helped me find from before, It "pushed" my text in the middle to the right even though the logo doesnt "touch" the text... how could i make the text come back, ignoring the logo and instead just stay where it was?
Not really.
There are few ways to use CSS.
You can make a separate file and load it by adding a respective tag in the HTML.
That's the approach I would recommend.
On you can use CSS inline, just like you did.
Using it inline will make it harder to propagate changes to all the elements.
For example if you have multiple h1s, you will have to put style for each one of them.
While in CSS file you can apply style to all h1s at once.
And if you change it - it also changes for all of them at once.
@whole goblet I'm not really into frontends, but I think you can set position for the logo to remove it from the document text flow.
It's also CSS. Something like position: absolute.
ahh okay thanks 😃
anyone use https://github.com/kennethreitz/responder
what's the easiest way to deploy flask online and host it locally?
Like host it from your local computer to the outside world?
yeah
Well it depends on what you want of it and what usage do you expect from your website.
But gunicorn+nginx should do the trick just fine.
It's only going to serve like 4 people lol
and just display some items in a database
I just finished making the app but need to deploy it now
If that's a tempory solution you may be able to get away with just it's own development server.
Although I would not recommend having it running to the outside world for an extended periods of time.
I mean the app.run() one.
It's going to be run all the time at a company
Fast, easy, dirty, slower and may be even insecure - app.run().
In the long run - gunicorn+nginx.
Or apache, whatever you prefer.
gunicorn is unix though?