Category Archives: Python

[Solved] Python2 error: 1File ““, line 1, in NameError: name ‘f…

Python 2

count = 0
while count < 3:
      user = input('>>>')
      pwd = input('>>>')
      if user == 'wy' and pwd == '123':
          print "welcome to login"
          break
      else:
          print "your username or password is wrong"
      count = count +1

The following output error is caused:

/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 “/Users/macmini-2/Desktop/AiGuXuan 2018-04-24 09-01-22/day1.py”
>>>f
Traceback (most recent call last):
File “/Users/macmini-2/Desktop/AiGuXuan 2018-04-24 09-01-22/day1.py”, line 30, in <module>
user = input(‘>>>’)
File “<string>”, line 1, in <module>
NameError: name ‘f’ is not defined

Process finished with exit code 1

Solution:

count = 0
while count < 3:
      user = raw_input('>>>')
      pwd = raw_input('>>>')
      if user == 'wy' and pwd == '123':
          print "welcome to login"
          break
      else:
          print "your username or password is wrong"
      count = count +1

Change input to raw_input

[Solved] Django cannot create an app after creating a project

F:\index>python manage.py startapp news
Traceback (most recent call last):
File “manage.py”, line 8, in <module>
from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named ‘django’

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File “manage.py”, line 14, in <module>
) from exc
ImportError: Couldn’t import Django. Are you sure it’s installed and available on your PYTHONPATH environment variable?Did you forget to activate a virtual environment?
After creating a django project, adding python manage.py startapp news gives the following error
Uninstall django and install it again, can’t fix it
python -m pip install django problem solved
F:\index>python -m pip install django
Collecting django
Using cached https://files.pythonhosted.org/packages/ab/15/cfde97943f0db45e4f999c60b696fbb4df59e82bbccc686770f4e44c9094/Django-2.0.7-py3-none-any.whl
Requirement already satisfied: pytz in c:\programdata\anaconda3\lib\site-packages (from django)
Installing collected packages: django
Successfully installed django-2.0.7
You are using pip version 9.0.1, however version 10.0.1 is available.
You should consider upgrading via the ‘python -m pip install –upgrade pip’ command.

[Solved] Fatal error in launcher: unable to create process using ‘”‘

 

Coexistence environment of python3 and python2 under win7

Installing a package with pip
When executing pip2 install xxx, an error is reported
Fatal error in launcher: Unable to create process using '"'

The same error is reported when executing pip3 install xxx
Fatal error in launcher: Unable to create process using '"'


Solution
python2 -m pip install XXX
python3 -m pip install XXX

This will allow you to use pip to install the module properly

Message: ‘geckodriver’ executable needs to be in PATH. [Solved]

Problem Description:

Execute the following code

# coding=utf-8
from selenium import webdriver

driver = webdriver.Firefox()
driver.maximize_window()
driver.implicitly_wait(2)

driver.get('https://www.baidu.com')
try:
    driver.find_element_by_id('kw')
    print('test pass: ID found')
except Exception as e:
    print('Exception found', format(e))

driver.quit()

Error:

Traceback (most recent call last):
File “E:/PythonSelenium/CSDN/004id.py”, line 4, in <module>
driver = webdriver.Firefox()
File “E:\Python35\lib\site-packages\selenium\webdriver\firefox\webdriver.py”, line 142, in __init__
self.service.start()
File “E:\Python35\lib\site-packages\selenium\webdriver\common\service.py”, line 81, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: ‘geckodriver’ executable needs to be in PATH.

Reason:

Message: ‘geckodriver’ executable needs to be in PATH.

Solution:

(1) test environment: Selenium 3.4.0 Firefox 56.0 Python3.5.2

(2) Download the corresponding driver for Firefox, portal https://github.com/mozilla/geckodriver/releases combined with the version of my browser need to download V 0.19.0

(3) Unzip the file to get the geckodriver.exe file and place it in the home directory. After re-running found that the problem has been solved.

Note: Pay attention to Firefox, Python environment variable settings.

[Solved] Python urlib2gaierror: [Errno 11004] getaddrinfo failed

Gaierror: get address info error. If the URL is incorrect or the proxy information is not configured correctly, this error will be reported

I wrote a very simple class to send HTTP requests. Sometimes it runs thousands of times without reporting an error. Sometimes it runs dozens of times without reporting the [11004] error at the beginning. Many tutorials have been found on the Internet, such as adding a disconnect mark on the header, or increasing the number of retries

So, it’s good to try again. If you find an error, sleep for two seconds and resend it

class HTTPsClient(object):
    def __init__(self, url):
        self.url = url
        self.session = requests.session()
 
    def send(self, data=None, **kwargs):
        flag = False
        while not flag:
            try:
                response = self.session.request(method='POST', url=self.url, data=data,**kwargs)
            except:
                print u'[%s] HTTP request failed!!! Preparing to resend....' % get_time()
                time.sleep(2)
                continue
            flag = True
        self.session.close()

It doesn’t have to be written as always retrying. You can also set the number of times to retrying

[Solved] An error occurred when paddlepaddle iterated data: typeerror: ‘function’ object is not iterative

Problem Description: when using the reader to read the training data, there is an error, and the error prompt is typeerror: ‘function’ object is not iterative

error message:

TypeError                                 Traceback (most recent call last)
<ipython-input-12-0b74c209241b> in <module>
      2 for pass_id in range(1):
----> 3     for batch_id, data in enumerate(train_reader):
      4         train_cost, train_acc = exe.run(program=fluid.default_main_program(),
      5                                         feed=feeder.feed(data),

TypeError: 'function' object is not iterable

Problem recurrence: when reading data in the loop, the reader defined by padding. Batch() iterates over the data, and enumerate() uses the defined variables. When the function is called, an error will be reported. The error code is as follows:

for batch_id, data in enumerate(train_reader):
    train_cost, train_acc = exe.run(program=fluid.default_main_program(),
                                    feed=feeder.feed(data),
                                    fetch_list=[avg_cost, acc])

Problem-solving: the same as a data reading function obtained by pad DLE. Batch() , the return value is a reader, and the reason for the above error is that it directly trains_ Reader variable, which refers to a function, so you need to add a bracket to get the return value reader of the function

for batch_id, data in enumerate(train_reader()):
    train_cost, train_acc = exe.run(program=fluid.default_main_program(),
                                    feed=feeder.feed(data),
                                    fetch_list=[avg_cost, acc])

In Python variables, when there are no parentheses, the function itself is called. It is a function object, and there is no need to wait for the function to be executed. With brackets, the result of the function is called, and the result of the function execution must be completed

[Django CSRF tutorial] solve the problem of forbidden (403) CSRF verification failed. Request aborted

Django Version: 1.11.15

Error reported for post request in django:
Forbidden (403)
CSRF verification failed. Request aborted.

Help
Reason given for failure:
CSRF cookie not set.

Method 1: Do not use CSRF authentication</strong
Disable sitewide (not recommended)
Remove the django.middleware.csrf.CsrfViewMiddleware middleware from MIDDLEWARE in settings.py
For example, the following configuration would remove the django.middleware.csrf.CsrfViewMiddleware
MIDDLEWARE = [
‘django.middleware.security.SecurityMiddleware’,
‘django.contrib.sessions.middleware.SessionMiddleware’,
‘django.middleware.common.CommonMiddleware’,
‘django.middleware.csrf.CsrfViewMiddleware’,
‘django.contrib.auth.middleware.AuthenticationMiddleware’,
‘django.contrib.messages.middleware.MessageMiddleware’,
‘django.middleware.clickjacking.XFrameOptionsMiddleware’,
]

Partially disabled (recommended)
Or you can add @csrf_exempt for views where you don’t want csrf protection
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def ajaxGetList(r):

Method 2: Use CSRF validation</strong

form form to add
{% csrf_token %}

views.py code
from django.template.context_processors import csrf
from django.http import HttpResponse
from django.template import Context, loader

def my_view(request):
c = {}
c.update(csrf(request))
# … view code here
return HttpResponse(loader.get_template(‘index.html’).render(c))

Older versions of the code.
from django.core.context_processors import csrf
from django.shortcuts import render_to_response
def my_view(request):
c = {}
c.update(csrf(request))
# … view code here
return render_to_response(“a_template.html”, c)

js code
Add a header of X_CSRFTOKEN when sending an ajax POST request
// using jQuery
var csrftoken = jQuery(“[name=csrfmiddlewaretoken]”).val();
or
var csrftoken = $.cookie(‘csrftoken’);
Code 1:
function submitForm(){
var user = $(‘#user’).val();
$.ajax({
url: ‘/csrf1.html’,
type: ‘POST’,
headers:{‘X-CSRFToken’: csrftoken},
data: { “user”:user},
success:function(arg){
console.log(arg);
}
})
}

Code 2.
// Go to the cookie to get the value
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader(“X-CSRFToken”, csrftoken);
}
}
});
function DoAjax(){
$.ajax({
url: ‘/csrf/’,
type: ‘POST’,
data: {‘k1’: ‘v1’},
success: function (data) {
console.log(data);
}
})
}

PS:
1.csrf decorator
Global.
Middleware django.middleware.csrf.CsrfViewMiddleware
Local.
from django.views.decorators.csrf import csrf_exempt,csrf_protect
@csrf_protect, enforce anti-cross-site request forgery for the current function, even if no global middleware is set in settings.
@csrf_exempt, disables cross-site request forgery prevention for the current function, even if the global middleware is set in settings.
2. django recommends using django.middleware.csrf.CsrfViewMiddleware for global control, and does not advocate using @csrf_protect for single-view control, as this may be missed. You can add @csrf_exempt if you don’t want csrf-protected views. Use CSRF authentication: add django.core.context_processors.csrf to the TEMPLATE_CONTEXT_PROCESSORS of the configuration file, or manually generate csrftoken and add it to the template context.
3. django 1.11 csrf official documentation: https://docs.djangoproject.com/en/1.11/ref/csrf/#django.views.decorators.csrf.csrf_protect

How to Solve Python flash_mysqldb Install error

Install mysqldb (pip3 install Flask-MySQLdb)error: EnvironmentError: mysql_config not found ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Or error: command ‘x86_64-linux-gnu-gcc’ failed with exit status 1

 

Solution:

Refer to the answer on Github (https://github.com/scrapy/scrapy/issues/2115#issuecomment-231849637), successfully solved.

with Python 3, you’ll need

sudo apt-get install python3 python-dev python3-dev build-essential libssl-dev libffi-dev libxml2-dev libxslt1-dev zlib1g-dev python3-pip

with Python 2, you’ll need

sudo apt-get install python-dev build-essential libssl-dev libffi-dev libxml2-dev libxslt1-dev zlib1g-dev python-pip

Pycharm introduces numpy error: ImportError: Importing the multiarray numpy extension module failed. Most likely you are trying to import a failed build of numpy.

The software is pychar with Anaconda installed

My initial error was that numpy could not be called in pychar, and the error was modulenotfounderror: no module named ‘numpy’. This problem was solved by the blog. In fact, we need to use Anaconda’s python.exe

But when you run the code:

import numpy as np

arr = np.random.randint(1, 9, size=9)
print(arr)

The following error occurred again:

File “C:\python\Anaconda3\lib\site-packages\numpy\core\__ init__. py”, line 26, in < module>
raise ImportError(msg)
ImportError:
Importing the multiarray numpy extension module failed. Most
likely you are trying to import a failed build of numpy.
If you’re working with a numpy git repo, try `git clean -xdf` (removes all
files not under version control). Otherwise reinstall numpy.

Or error, after their own exploration, found a solution, the original version of their numpy is too low! The solution is as follows:

 

How to update?The best way is to use anacon to update all of them uniformly without making mistakes. The method is as follows:

Step 1: first, start cmd.exe as an administrator
Step 2: to upgrade CONDA (you need to upgrade CONDA before upgrading Anaconda) is: CONDA update CONDA
Step 3: to upgrade anconda is: CONDA update Anaconda
Step 4: to upgrade Spyder is: CONDA update Spyder

Step 3: to upgrade Anaconda

Then restart pychar and run the code:

import numpy as np

arr = np.random.randint(1, 9, size=9)
print(arr)

Finally it worked! And when you type pycharm there are also function parameters and other prompts, by the way in the windows environment: ctrl+p will come up with parameter prompts.
Run the results.

[1 2 2 4 7 1 8 7 4]