Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Sad Panda
Sep 22, 2004

I'm a Sad Panda.

tef posted:

It's worth pointing out that many of these algorithms operate on *fixed length arrays* not *python lists*. When you're calling pop, insert, append, you're changing the length of the list, as well as changing the list. With these old algorithms, you probably want to stick to arr[0] = .....

Or maybe, build a new list entirely. The code always gets a bit tricky when you're using one data structure in place of two:

For example: this operates like an insert sort (find smallest, put at end of new list), but it doesn't re-use the front old list to store the values

code:
arr = []
while unsorted:
    smallest = min(unsorted)
    idx = unsorted.index(smallest)
    arr.append(unsorted.pop(idx))
When you're looking at these algorithms, you should try and think about the strategy (over arching goal) or tactics (actions towards goal) they take.

Insertion sort divides the list into two pieces, the smallest element and all elements larger than it. Bubble sort tries to make the list slightly less unsorted with each pass, moving elements to the right position. Both of these strategies can be adapted to build other sorting algorithms, and sometimes the tactics from the 60's and 70's aren't as valid today

You could make different tactics: like keeping the min, max as you scan through the list, and build up a new list from either end. Or perhaps change the strategy: break the list into (smaller than, bigger than) rather than (min, bigger than). Then sort either half.

You can start to develop a feel for different ways to sort structures. It might be worth looking at how python does it too, it uses a wonderful trick: Break the list into pre-sorted chunks and merge them. It's a little of both worlds: Scanning through a list to find out of place elements, and breaking the list down into smaller pieces to operate on.

Thanks for the explanation. The reason behind i is that I'm planning on teaching CS in the UK and it's part of the school curriculum. They don't have to be able to code it, just have an idea of how it works and be able to trace it.

The Python explanation sounds like a merge sort. I'll do some reading about it. I've not yet written the code for my merge sort. I'm not really sure how to code it to make a list for each element. I'm sure some Googling would give me an idea.

Adbot
ADBOT LOVES YOU

Hughmoris
Apr 21, 2007
Let's go to the abyss!
I'm trying to figure out how this torrent name parsing library works, and I'm stumped when looking at the code. I get the gist of it but I don't fully understand how it goes about it.

https://github.com/divijbindlish/parse-torrent-name/blob/master/PTN/parse.py

What's a good method of attack when trying to figure out something like this? Toss in print statements everywhere? Does PyCharm have functionality specifically for this that I should explore?

The Fool
Oct 16, 2003


I don’t use pycharm, but I would start here: https://www.jetbrains.com/help/pycharm/debugging.html

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Assuming PyCharm has the same basic debugging capabilities as IntelliJ, you can add breakpoints wherever, then right-click them and uncheck pause execution (or whatever), and add your own print statement in the "execute this" bit - you can include variables and all that. It's like adding print statements without sticking them in the code

But stepping through and watching what happens is your best bet

Proteus Jones
Feb 28, 2013



baka kaba posted:

Assuming PyCharm has the same basic debugging capabilities as IntelliJ, you can add breakpoints wherever, then right-click them and uncheck pause execution (or whatever), and add your own print statement in the "execute this" bit - you can include variables and all that. It's like adding print statements without sticking them in the code

But stepping through and watching what happens is your best bet

It has all that. My absolute favorite thing is the just being able to display variable contents at various break points. It’s been invaluable in helping me zero in on logical errors I’ve made.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

My fav thing is being able to reach in and change the value of variables (even by executing some arbitrary code) and then set it running again

Scaevolus
Apr 16, 2007

Hughmoris posted:

I'm trying to figure out how this torrent name parsing library works, and I'm stumped when looking at the code. I get the gist of it but I don't fully understand how it goes about it.

https://github.com/divijbindlish/parse-torrent-name/blob/master/PTN/parse.py

What's a good method of attack when trying to figure out something like this? Toss in print statements everywhere? Does PyCharm have functionality specifically for this that I should explore?

PDB or IPython's debugger (ipdb) would work well too, and you don't need to learn a full IDE: https://www.safaribooksonline.com/blog/2014/11/18/intro-python-debugger/

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Conditional breakpoints in PyCharm are good things too. (right-click the breakpoint in the gutter)



(randomly googled image. Being a sane human being I use a dark theme)

Cingulate
Oct 23, 2012

by Fluffdaddy
... there is a non-dark theme in pycharm?

Boris Galerkin
Dec 17, 2011

I don't understand why I can't harass people online. Seriously, somebody please explain why I shouldn't be allowed to stalk others on social media!

Cingulate posted:

... there is a non-dark theme in pycharm?

The default one is non-dark and is the one I use because the dark themes all blow.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Stop saying wrong things!

(I used Darkula and monokai for a long time, but a few months ago I switched to the Material UI theme/plugin)

DoNotFeedTheBear
Sep 13, 2007
I believe you can set up PyCharm to pause on any exception, or even just unhandled ones, right? I know in Visual Studio and Visual Code you can. Not sure about Spyder though.

porksmash
Sep 30, 2008
Yeah you can - Ctrl-Shift-F8 to bring up the options.

Boris Galerkin
Dec 17, 2011

I don't understand why I can't harass people online. Seriously, somebody please explain why I shouldn't be allowed to stalk others on social media!
Is there a read the docs style theme for jupyter notebooks? The regular theme is kinda plain and I really like the rtd theme.

KernelSlanders
May 27, 2013

Rogue operating systems on occasion spread lies and rumors about me.

Sad Panda posted:

I was learning some Comp Sci and that involved learning about linear search, binary search, bubble sort, insertion sort and merge sort. I decided that the best way to make sure that I understand them was to code them.

...

It could print a bit less, but that's just there as debug at the minute. That and it's fun to watch things bubble along.

Yeah, there's some extra printing, and printing the whole list makes it N^3 instead of N^2. I'm not sure why you're doing so much extraneous stuff though. In python, bubble sort is just:

Python code:
def bubble_sort(x):
    for i in range(0, n):
        for j in range(1, i+1):
            if x[j-1] > x[j]:
                x[j-1], x[j] = x[j], x[j-1]

Hadlock
Nov 9, 2004

I'm getting ready to write, at least two microservices for deploying and maintaining state of an app, probably another 3-5 microservices related to deploying other apps. These will just be serving up json from a standard restful api using basic auth deep inside the protected network and not accessible outside the company. No UI or twitter for zombies, etc.

I'm fairly happy with using Flask at this point. It seems like Flask is the go-to library for microservices? I am looking at using PeeWee as my ORM and then connecting to a postgres db.

Is this a pretty good solution? Peewee seems actively developed despite having a fairly small user base. The big plus for me is that it's especially straightforward.

Other options include Flask/SQLAlchemy, SQLAlchemy being more difficult to use and a lot meatier.

Option C is something in the Django-world. Django has a fair bit of rails-magic to it, and I'm trying to imagine a future where my ops buddies can debug the code without having to call me when I'm on vacation in the bahamas someday.

Am I going to bet happy with Python/Flask/Peewee?

My predecessor used Cherry Py for something similar at another company.

M. Night Skymall
Mar 22, 2012

Hadlock posted:

I'm getting ready to write, at least two microservices for deploying and maintaining state of an app, probably another 3-5 microservices related to deploying other apps. These will just be serving up json from a standard restful api using basic auth deep inside the protected network and not accessible outside the company. No UI or twitter for zombies, etc.

I'm fairly happy with using Flask at this point. It seems like Flask is the go-to library for microservices? I am looking at using PeeWee as my ORM and then connecting to a postgres db.

Is this a pretty good solution? Peewee seems actively developed despite having a fairly small user base. The big plus for me is that it's especially straightforward.

Other options include Flask/SQLAlchemy, SQLAlchemy being more difficult to use and a lot meatier.

Option C is something in the Django-world. Django has a fair bit of rails-magic to it, and I'm trying to imagine a future where my ops buddies can debug the code without having to call me when I'm on vacation in the bahamas someday.

Am I going to bet happy with Python/Flask/Peewee?

My predecessor used Cherry Py for something similar at another company.

I'm in the process of doing something similar, and I've pretty much also decided Flask is the way to go. I think Django REST Framework looks pretty nice if you need the features it provides like a built-in ORM, more robust user authentication methods, web browsable API, throttling, plenty of other stuff I care even less about. I don't really need any of that though and it doesn't sound like you do either, and Flask is nice since it's a lot easier to integrate whatever ORM you're comfortable with and is just lighter. I think DRF'd be great if I were more familiar with django already, or the API were public facing at all.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I just posted this in the web dev thread:

Thermopyle posted:

A good resource for learning Python is the Python thread. We're all very helpful over there :D.

Also, what Lumpy said about Django vs Flask is right. But there's a wrinkle. Django can be unopinionated, its just that people tend to use Django because it can do out of the box what you've got to glom a bunch of libraries together to do in Flask.

Here's a complete Django project for serving a Hello World page (actually from an older version but the idea is the same on Django 2.0):

Python code:
import sys


from django.conf import settings


settings.configure(
    DEBUG=True,
    SECRET_KEY='thisisthesecretkey',
    ROOT_URLCONF=__name__,
    MIDDLEWARE_CLASSES=(
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ),
)


from django.conf.urls import url
from django.http import HttpResponse


def index(request):
    return HttpResponse('Hello World')


urlpatterns = (
    url(r'^$', index),
)


if __name__ == "__main__":
    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

Personally, I would always use Django because it's easy to use it in as lightweight a manner as Flask, but its easier to add more features if you need them.

That is not to say anything bad about Flask...it's a great project.

Dominoes
Sep 20, 2007

Same; Django had a steep learning curve, but for me, at least, it's easier to set up a Django project than try to make Flask plugins play well together. Most of the projects I've worked on involve making a website or REST api, so this may not be applicable to other uses.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Dominoes posted:

Same; Django had a steep learning curve, but for me, at least, it's easier to set up a Django project than try to make Flask plugins play well together. Most of the projects I've worked on involve making a website or REST api, so this may not be applicable to other uses.

FWIW, Django probably had a steep learning curve to you because you were also (implicitly) learning how web application servers worked.

You would likely now have a much easier time learning some other web app server even if it was, by some objective standard, "harder" to learn than Django just because you understand the space now.

(assuming by "steep learning curve" you colloquially mean "hard to learn" rather than its technical meaning of "quick to learn")

Thermopyle fucked around with this message at 20:15 on Mar 26, 2018

The March Hare
Oct 15, 2006

Je rêve d'un
Wayne's World 3
Buglord
Django really isn't that hard, I've never totally understood people saying that it is. It has some up-front default config that you have to figure out but the documentation is pretty solid and none of the concepts in Django are novel.

Dominoes
Sep 20, 2007

Thermopyle posted:

FWIW, Django probably had a steep learning curve to you because you were also (implicitly) learning how web application servers worked.
Nailed it. Also trying to get Chef/Vagrant working per the tutorial I used; never sorted that out!

The March Hare posted:

Django really isn't that hard, I've never totally understood people saying that it is. It has some up-front default config that you have to figure out but the documentation is pretty solid and none of the concepts in Django are novel.
It has an extensive API, but the official tutorial's good about pointing to the necessities. Your point about the default config makes sense too; you need to make some (I imagine fairly standard) changes to settings.py to get started. (eg allowed hosts; templates and static files; database; adding your app to INSTALLED_APPS, dealing with CSRF/CORS if you're using DRF)

There's a lot of specific syntax to memorize, but most of it's provided by the tutorial.

Dominoes fucked around with this message at 19:43 on Mar 26, 2018

The March Hare
Oct 15, 2006

Je rêve d'un
Wayne's World 3
Buglord
Now that I think about it, I can see being new and being totally confused by CBVs/generic CBVs/function views. I think models are fairly reasonable (especially now that you don't need an outside library for migrations), functional views are totally intuitive in their machinations, urls aren't that bad as long as you read the docs, and forms are terrible even if you do read the documentation.

Data Graham
Dec 28, 2009

📈📊🍪😋



The March Hare posted:

Now that I think about it, I can see being new and being totally confused by CBVs/generic CBVs/function views. I think models are fairly reasonable (especially now that you don't need an outside library for migrations), functional views are totally intuitive in their machinations, urls aren't that bad as long as you read the docs, and forms are terrible even if you do read the documentation.

The docs seem to be downplaying function-based views as much as they can; if they aren't planning to deprecate them outright I feel like they're going to turn into a semi-supported feature that just confuses everyone down the line.

Dominoes
Sep 20, 2007

The March Hare posted:

I think models are fairly reasonable (especially now that you don't need an outside library for migrations)
That was another stumbling block from earlier Django versions - "You mean I can't change my database unless I install an addon, and when I do, it's a gamble if my site will work again without resetting the DB?

huhu
Feb 24, 2006
Anyone have any recommendations for resources for learning MicroPython (with the ESP2866)? I see a few books on Amazon but none look promising and I can't really find good Youtube videos or other courses online.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Data Graham posted:

The docs seem to be downplaying function-based views as much as they can; if they aren't planning to deprecate them outright I feel like they're going to turn into a semi-supported feature that just confuses everyone down the line.

Django FBV's won't be depracated, because all Django views are function based views...even the so-called class-based views which are decomposed to a regular function by Django. That's what the as_view method on CBVs does.

This is because a Django view is, by definition, a callable that takes an HttpRequest and returns an HttpResponse.

Seventh Arrow
Jan 26, 2005

vikingstrike posted:

If you need to create a DataFrame, and pyspark has a DataFrame creator function that gives you the desired output, I'm not sure why you'd try to roll your own. Turning CSVs into DataFrames is some of the most basic functionality of a library like this.

So this was a ways back, but I realized why I had such a convoluted way of importing CSV's...apparently pandas dataframes and Spark dataframes are different things and have to be handled differently. Spark has similar things to pandas, but working with CSV's seems to be more of a hassle .

SnatchRabbit
Feb 23, 2006

by sebmojo
Crossposting from the AWS thread but I'm a Python noob and I'm trying to parse some JSON data inside a notification event.

Has anyone used Lambda to parse SNS event? I've been trying to parse an AWSConfig rule's SNS events and using the data to do various things. I'm able to parse the data up to a point, but I can't seem to get the message JSON data that I want. I'm using python 2.7, and json, boto3 imports. I think my issue is the JSON is being read as a single key. Anyone know how to do this?

code:
from __future__ import print_function
import boto3
import json

def lambda_handler(event, context):
   message = event['Records'][0]['Sns']['Message']
   message = json.loads(message)
   print(message)


output:
code:
{u'configRuleNames': [u'restricted-sshv2'], u'awsRegion': u'us-west-2', u'messageType': u'ConfigRulesEvaluationStarted', u'recordVersion': u'1.0', u'notificationCreationTime': u'2018-03-29T22:08:34.631Z', u'awsAccountId': u'########'}
event data: https://dumptext.com/jyTfBcNl

SnatchRabbit fucked around with this message at 23:29 on Mar 29, 2018

Tigren
Oct 3, 2003

SnatchRabbit posted:

Crossposting from the AWS thread but I'm a Python noob and I'm trying to parse some JSON data inside a notification event.

Has anyone used Lambda to parse SNS event? I've been trying to parse an AWSConfig rule's SNS events and using the data to do various things. I'm able to parse the data up to a point, but I can't seem to get the message JSON data that I want. I'm using python 2.7, and json, boto3 imports. I think my issue is the JSON is being read as a single key. Anyone know how to do this?

code:
from __future__ import print_function
import boto3
import json

def lambda_handler(event, context):
   message = event['Records'][0]['Sns']['Message']
   message = json.loads(message)
   print(message)


output:
code:
{u'configRuleNames': [u'restricted-sshv2'], u'awsRegion': u'us-west-2', u'messageType': u'ConfigRulesEvaluationStarted', u'recordVersion': u'1.0', u'notificationCreationTime': u'2018-03-29T22:08:34.631Z', u'awsAccountId': u'########'}
event data: https://dumptext.com/jyTfBcNl

What are you hoping for the end result to be? message = json.loads(message) returns a dict, and printing it will display the whole thing as a string.

SnatchRabbit
Feb 23, 2006

by sebmojo

Tigren posted:

What are you hoping for the end result to be? message = json.loads(message) returns a dict, and printing it will display the whole thing as a string.

I want the message to be the json portion of the event that starts with message so i can grab individual values out of it.

Dr Subterfuge
Aug 31, 2005

TIME TO ROC N' ROLL
That's what json.loads has done. Printing it just displays message (which is now a python dict) as string so it can be displayed.

Dr Subterfuge fucked around with this message at 00:53 on Mar 30, 2018

SnatchRabbit
Feb 23, 2006

by sebmojo

Dr Subterfuge posted:

That's what json.loads has done. Printing it just displays message (which is now a python dict) as string so it can be displayed.

Right, but what I need is message to be this portion, in JSON, so I can use individual values (strings) like resourceID, and put that in a statement later. Not sure that makes sense, like I said I'm terrible with python.

code:
{"awsAccountId":"#######","configRuleName":"restricted-sshv2","configRuleARN":"arn:aws:config:us-west-2:########:config-rule/config-rule-htirkv","resourceType":"AWS::EC2::SecurityGroup","resourceId":"sg-######","awsRegion":"us-west-2","newEvaluationResult":{"evaluationResultIdentifier":{"evaluationResultQualifier":{"configRuleName":"restricted-sshv2","resourceType":"AWS::EC2::SecurityGroup","resourceId":"sg-#######"},"orderingTimestamp":"2018-03-29T02:03:20.664Z"},"complianceType":"NON_COMPLIANT","resultRecordedTime":"2018-03-29T02:47:53.647Z","configRuleInvokedTime":"2018-03-29T02:47:53.207Z","annotation":null,"resultToken":null},"oldEvaluationResult":null,"notificationCreationTime":"2018-03-29T02:47:54.468Z","messageType":"ComplianceChangeNotification","recordVersion":"1.0"}

Data Graham
Dec 28, 2009

📈📊🍪😋



Unless I'm misunderstanding you, you already have everything you need. message is currently a dict with all the values that were loaded in from the JSON. So you can access resourceID like

message['resourceID']

Seventh Arrow
Jan 26, 2005

I'm working on a "coding test" for a job application but unless I'm missing something I don't think they've given me enough to work with. Here's the instructions from the email:

quote:

Problem description:

Given the provided URLs to images of vehicles and the API documentation please construct a request to submit the images to the API using the credentials given, poll for job completion and get the results from the finished job.
The Image API classifies images, provides coordinates of a box that surrounds the primary vehicle in the image and enhances the image by blurring the background to highlight the primary vehicle.
Use PHP, Python or Java to implement your solution.
Basic error handling should be implemented, but no heroics necessary.
The program should take the Image URLs as input, as parameters, stdin, read from file, etc.
API responses should be logged
Provide a ZIP/archive of the program code, logged output and resulting images downloaded from the API results.

Then there's a link to five images and this is the API "documentation":

quote:

PhotoAI API

USAGE FLOW:

1. Send request to optimize images.
a. Receive a response with token
2. Periodically send token to server
a. Receive a status of request
b. Alternatively, you can get the list of requests and tokens
3. When status is complete, make the final request with the token
4. Receive a full processed response.
5. Images will be hosted at the new ​"modifiedUrl"​ for you to download for 7 days.

Note: ​You can have many requests queued at same time, so there is no need to wait for one to finish before sending subsequent requests.
Individual requests should be limited to 1,000 images at a time for optimal efficiency. The processing time for a batch of 1,000 images is approximately 20 minutes

User Credentials:

username: ​<these values will be given in a different document>
password: ​<these values will be given in a different document>
All requests must include basic authentication in the header
For example, using cURL you can set basic authentication with:
curl -u username:password

I mean, I think some of this stuff can be executed via curl/requests but don't they need to provide some details on how to interact with their API? Just speaking of Amazon, they have buttloads of documentation on how to use boto to work with S3, EC2, IAM security and all that stuff. The API seems to be a specialized image-recognition app so I don't think generic REST commands will do it. Am I missing something or do I really need to send them a reply asking for more info?

Dr Subterfuge
Aug 31, 2005

TIME TO ROC N' ROLL

SnatchRabbit posted:

Right, but what I need is message to be this portion, in JSON, so I can use individual values (strings) like resourceID, and put that in a statement later. Not sure that makes sense, like I said I'm terrible with python.

code:
{"awsAccountId":"#######","configRuleName":"restricted-sshv2","configRuleARN":"arn:aws:config:us-west-2:########:config-rule/config-rule-htirkv","resourceType":"AWS::EC2::SecurityGroup","resourceId":"sg-######","awsRegion":"us-west-2","newEvaluationResult":{"evaluationResultIdentifier":{"evaluationResultQualifier":{"configRuleName":"restricted-sshv2","resourceType":"AWS::EC2::SecurityGroup","resourceId":"sg-#######"},"orderingTimestamp":"2018-03-29T02:03:20.664Z"},"complianceType":"NON_COMPLIANT","resultRecordedTime":"2018-03-29T02:47:53.647Z","configRuleInvokedTime":"2018-03-29T02:47:53.207Z","annotation":null,"resultToken":null},"oldEvaluationResult":null,"notificationCreationTime":"2018-03-29T02:47:54.468Z","messageType":"ComplianceChangeNotification","recordVersion":"1.0"}

Like Data Graham said getting resourceID from message would just be message['resourceID']. If you need to turn it back into a JSON string you would do json.dumps(message)

breaks
May 12, 2001

SnatchRabbit posted:

Right, but what I need is message to be this portion, in JSON, so I can use individual values (strings) like resourceID, and put that in a statement later. Not sure that makes sense, like I said I'm terrible with python.

As mentioned in the prior replies there isn't anything obviously wrong with your Python, but the example response you provided isn't consistent with the dict you pasted. For example, the JSON has a configRuleName key with a string value, and the dict has a configRuleNames key with a list of strings value (it only has one string). The structure of JSON example you gave is clearly not entirely the same as the structure of whatever JSON you are passing to json.loads.

I don't know much about AWS, but determining the cause of that discrepancy is where I would start.

SnatchRabbit
Feb 23, 2006

by sebmojo

Data Graham posted:

Unless I'm misunderstanding you, you already have everything you need. message is currently a dict with all the values that were loaded in from the JSON. So you can access resourceID like

message['resourceID']

Yup, this worked like a charm. Thanks, everyone!

Seventh Arrow
Jan 26, 2005

Seventh Arrow posted:

I'm working on a "coding test" for a job application but unless I'm missing something I don't think they've given me enough to work with. Here's the instructions from the email:


Ok, so it looks like there was more to the pdf than I initially thought. Woops!

I've run into a snag, though...they want the images submitted to the API using the format in this example:

quote:

1. SUBMIT REQUESTS
Host - https://photoai.lotlinx.com
POST /images/optimize

POST body must be in the following format:
code:

[
 {
 "dealerId":12345,
 "vehicles":[
 {
 "id": 55,
 "images" : [
 {
 "imageId": 91,
 "imageUrl":"https://img.lotlinx.com/...273984882.jpg"
 },
 {
 "imageId": 92,
 "imageUrl":"https://img.lotlinx.com/...273984883.jpg"
 }
 ]
 }
 ]
 }
]

So I tried to come up with my own code:

code:
import requests
from requests.auth import HTTPBasicAuth

url = 'https://photoai.lotlinx.com/images/optimize'
files = [{"dealerid":12345, "vehicles":[ { "id":55, "images" : [ {"imageId": 1, "imageURL":"https://img.lotlinx.com/vdn/7416/jeep_wrangler%20unlimited_2014_1C4BJWFG3EL326863_7416_339187295.jpg"}, {imageID: 2, "imageURL":"https://img.lotlinx.com/vdn/7416/jeep_wrangler%20unlimited_2014_1C4BJWFG3EL326863_7416_2_339187295.jpg"}]}]}]
r = requests.post(url, files=files, auth=('username', 'password'))
r.status_code == requests.codes.ok
But I get the error: "NameError: name 'imageID' is not defined"

Does it maybe have to do with the way that the string is formatted?

Adbot
ADBOT LOVES YOU

Dr Subterfuge
Aug 31, 2005

TIME TO ROC N' ROLL
You have a typo in image 2.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply