小编cod*_*321的帖子

ImportError:没有名为'encodings'的模块

我最近重新安装了ubuntu并升级到16.04并且无法使用python:

$ python manage.py runserver
Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
Aborted
Run Code Online (Sandbox Code Playgroud)

此时,python本身不起作用

$ python
Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
Aborted
Run Code Online (Sandbox Code Playgroud)

即使这个建议不再有效:

unset …
Run Code Online (Sandbox Code Playgroud)

python development-environment virtualenv python-3.x macos-catalina

83
推荐指数
6
解决办法
14万
查看次数

点击API时curl vs python"requests"

我试图为我的帐户点击Bitbucket API,成功的尝试看起来像:

curl --user screename:mypassword https://api.bitbucket.org/1.0/user/repositories

在命令行中.在python中,我尝试:

import requests
url = 'https://api.bitbucket.org/1.0/user/repositories'
Run Code Online (Sandbox Code Playgroud)

然后

r = requests.post(url, data={'username': myscreename, 'password':mypassword})
Run Code Online (Sandbox Code Playgroud)

r = requests.post(url, data="myscreename:mypassword")
Run Code Online (Sandbox Code Playgroud)

r = requests.post(url, data={"user": "myscreename:mypassword"})
Run Code Online (Sandbox Code Playgroud)

都得到405错误.API为https://confluence.atlassian.com/display/BITBUCKET/Use+the+Bitbucket+REST+APIs

我想知道:

  1. 我在请求版本中做错了什么,它们看起来与我的curl尝试类似

  2. 请求curl和python请求模块有什么区别?在使用curl示例读取API然后在python中编写它时,我可以识别哪种一般模式?

谢谢

回答:

它需要正确的标题

https://answers.atlassian.com/questions/18451025/answers/18451117?flashId=-982194107

更新:

# ===============
# get user
# ===============
import requests
import json

# [BITBUCKET-BASE-URL], i.e.: https://bitbucket.org/
url = '[BITBUCKET-BASE-URL]/api/1.0/user/'
headers = {'Content-Type': 'application/json'}

# get user
# [USERNAME], i.e.: myuser
# [PASSWORD], i.e.: itspassword
r = requests.get(url, auth=('[USERNAME]', '[PASSWORD]'), headers=headers)
print(r.status_code) …
Run Code Online (Sandbox Code Playgroud)

python curl bitbucket-api python-requests

19
推荐指数
1
解决办法
3万
查看次数

django admin登录突然要求csrf令牌

几分钟前我很容易登录我的django管理控制台.我必须在以超级用户身份登录时导致此错误的某些地方进行了更改:

禁止(403)CSRF验证失败.请求中止.

这个错误让我措手不及,因为我整晚都在登录.为什么我突然需要一个用于管理员登录的csrf令牌?你会认为签到表格已经有了.这是我的admin.py:

from django.contrib import admin
from accounts.models import Image, Category, UserProfile

class ImageAdmin(admin.ModelAdmin):
    list_display    = ["__unicode__", "title", "created"]

admin.site.register(Image, GenericImageAdmin)

class CategoryAdmin(admin.ModelAdmin):
    list_display    = ["category"]

admin.site.register(Category, CategoryAdmin)

admin.site.register(UserProfile)
Run Code Online (Sandbox Code Playgroud)

django

17
推荐指数
3
解决办法
1万
查看次数

'function'对象没有属性'as_view'

我试图使用基于类的视图,并得到一个奇怪的错误.我使用视图的方式似乎是正常的方式:

配料/ models.py:

from django.db import models
from django.utils import timezone


class Ingredient(models.Model):
    name        = models.CharField(max_length=255)
    description = models.TextField()

    def get_prices():
        purchases   = self.purchase_set.all()
        prices      = [purchase.price for purchase in purchases]
Run Code Online (Sandbox Code Playgroud)

配料/ views.py:

from django.shortcuts           import render, render_to_response, redirect
from django.http                import HttpResponse, HttpResponseRedirect
from django.views.generic.edit  import CreateView
from .models                    import Ingredient, Purchase

def IngredientCreateView(CreateView):
    model = Ingredient
    fields = ['all']
Run Code Online (Sandbox Code Playgroud)

配料/ urls.py:

from django.conf.urls import patterns, include, url

from ingredients.views import IngredientCreateView

urlpatterns = patterns('',            
    url(r'^new_ingredient$',          IngredientCreateView.as_view(),             name='new-ingredient'),
) …
Run Code Online (Sandbox Code Playgroud)

python django django-class-based-views

17
推荐指数
3
解决办法
3万
查看次数

调用browserHistory.push("/ url")后componentDidMount没有运行

我有一个问题,我会在登录后将用户发送到react-router路由,具体取决于以下内容:

        ...
        //check login
        browserHistory.push(self.props.destination_url);
Run Code Online (Sandbox Code Playgroud)

我期待着componentDidMount运行,因为自从我加载应用程序以来,这个组件还没有出现在屏幕上,但它不会.如果我单击导航栏中的链接(react-router链接),则会componentDidMount运行.

由于browserHistory.push(self.props.destination_url);路由更改,我只需要在屏幕上显示此组件时进行API调用.我尝试过类似的东西

<Router createElement={ (component, props) =>
{
  const { location } = props
  const key = `${location.pathname}${location.search}`
  props = { ...props, key }
  return React.createElement(component, props)
} }/>
Run Code Online (Sandbox Code Playgroud)

此处组件在路由参数更改不起作用时不会重新装入.

这里http://busypeoples.github.io/post/react-component-lifecycle/显示"on mount","on unmount","on state change"或"on props changes".我没有看到任何适用于此的内容.是否存在将在此browserHistory推送转换后运行的生命周期方法?谢谢

我一直在尝试随机生命周期方法并且componentWillUpdate确实运行browserHistory.push但是它运行了数百次,完全减慢了应用程序的速度.我假设我在其中做的事情导致了几乎无限的循环:

componentWillUpdate() {
    console.log('it ran componentWillUpdate');
    if (this.props.email) {

        console.log('firing off /api/userInfo');
        let self = this;
        axios.post('/api/userInfo', {email: this.props.email})
          .then(function (response) { …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-router

11
推荐指数
1
解决办法
2918
查看次数

为什么有些包含在Django中需要字符串,还有其他变量名称?

参考Django书,第3章:

from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^mysite/', include('mysite.foo.urls')),
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    # url(r'^admin/', include(admin.site.urls)),
)
Run Code Online (Sandbox Code Playgroud)

是什么决定了为什么一个东西被包含为字符串,另一个被包含为常规变量?为什么admin.site.urls但不是'admin.site.urls'?所有其他include的都包含在字符串中...我在这里看不到逻辑模式.

python django url urlconf

10
推荐指数
1
解决办法
479
查看次数

渲染花括号作为纯文本react/jsx

我在React中将{和}显示为文本时遇到问题.我看到一个类似的问题,有人说将整个字符串包裹在curlies中,但这不起作用:

let queries_block = this.state.previous_queries.map((dataset) => {
            return (<p>{"{{}}"}<p>)
        });

        if (results) {
            results_block = (
                <div>
                    <p>Queries:</p>
                    {queries_block}
                    <br/><br/>
                    <p>Results: {results_count}</p>
                    <JSONPretty id="json-pretty" json={results}></JSONPretty>
                </div>
            );
        } else {
            results_block = null;
        }
Run Code Online (Sandbox Code Playgroud)

return (<p>{"{{}}"}<p>)原因

ERROR in ./src/components/app.js
Module build failed: SyntaxError: Unexpected token, expected } (47:13)

  45 |                     <JSONPretty id="json-pretty" json={results}></JSONPretty>
  46 |                 </div>
> 47 |             );
     |              ^
  48 |         } else {
  49 |             results_block = null;
  50 |         }

 @ ./src/index.js 15:11-38 …
Run Code Online (Sandbox Code Playgroud)

javascript jsx reactjs

10
推荐指数
4
解决办法
6214
查看次数

"PermissionError:[Errno 13]权限被拒绝:'/ usr/lib/python3.5/site-packages'"安装Django

我不能在Ubuntu上安装基本的Django包.我刚刚删除了virtualenv并重新制作了它.pip3install=pip3 install -r requirements.txt

[mything] cchilders@cchilders-desktop:~/projects/mything (master) 
$ cat requirements.txt 
Django==1.10.1
django-filter
djangorestframework
psycopg2
twilio
ipdb
ipython


[mything] cchilders@cchilders-desktop:~/projects/mything (master) 
$ pip3install 
Collecting Django==1.10.1 (from -r requirements.txt (line 1))
  Using cached Django-1.10.1-py2.py3-none-any.whl
Collecting django-filter (from -r requirements.txt (line 2))
  Using cached django_filter-0.15.2-py2.py3-none-any.whl
Requirement already satisfied (use --upgrade to upgrade): djangorestframework in /home/cchilders/.local/lib/python3.5/site-packages (from -r requirements.txt (line 3))
Requirement already satisfied (use --upgrade to upgrade): psycopg2 in /usr/lib/python3/dist-packages (from -r requirements.txt (line 4))
Collecting twilio (from -r requirements.txt …
Run Code Online (Sandbox Code Playgroud)

python django pip virtualenv django-1.10

9
推荐指数
2
解决办法
4万
查看次数

ElementNotVisibleException:消息:元素当前不可见... selenium(python)

我正在使用python的selenium获取那些恼人的元素是不可见的异常,而元素是活动的,选择的和闪烁的.

问题是在页面上制作一个jfiddle,所以这里不是制作小提琴本身,而是在你的ipython终端登录并拥有一个webdriver(名为'driver')的切割和粘贴方式(输入用户名和密码)进入ipython,而不是页面):

https://gist.github.com/codyc4321/787dd6f62e71cc71ae83

现在有一个驱动程序,你登录jsfiddle,我在这里做的一切都失败了,除了第一次选择框(让我说我想把CSS放在CSS框中):

https://gist.github.com/codyc4321/f4c03c0606c2e3e4ff5b

粘贴activate_hidden_element并在第一个代码行中看到CSS面板亮起.出于某种原因,这个突出显示的面板"不可见",您无法粘贴和编码.该项目是

  <div class="window top" id="panel_css" data-panel_type="css">
    <textarea id="id_code_css" rows="10" cols="40" name="code_css"></textarea>
    <a href="#" class="windowLabel" data-panel="css">
      <span class="label">CSS</span><i class="bts bt-gear"></i>
    </a>
  </div>
Run Code Online (Sandbox Code Playgroud)

所有其他项目(HTML,JS)基本相同.为什么这个活动框不允许文本粘贴?谢谢

解:

我使这项服务工作的丑陋方式是手动伪造剪切和粘贴:

css_content = get_inline_content_and_remove_tags(webpage_content, 'style')

js_content = get_inline_content_and_remove_tags(webpage_content, 'script')

webpage_content = # ...clean cruft...

def copy_paste_to_hidden_element(content=None, html_id=None):
    pyperclip.copy(content)
    activate_hidden_element(html_id=html_id, driver=driver)
    call_sp('xdotool key from+ctrl+v')
    time.sleep(1)

copy_paste_to_hidden_element(content=webpage_content, html_id="panel_html")
copy_paste_to_hidden_element(content=js_content, html_id="panel_js")
copy_paste_to_hidden_element(content=css_content, html_id="panel_css")
Run Code Online (Sandbox Code Playgroud)

它确实有效,唯一的小问题是它无法在后台运行,我需要单独离开屏幕大约30秒

javascript python selenium selenium-webdriver

8
推荐指数
1
解决办法
1570
查看次数

ImportError:安装pip时没有名为urllib3的模块

我有virtualenvwrapper需要重新安装PIP作为第一步的问题,我得到关于urllib3一个奇怪的抱怨:

$ python get-pip.py 
Traceback (most recent call last):
  File "get-pip.py", line 19177, in <module>
    main()
  File "get-pip.py", line 194, in main
    bootstrap(tmpdir=tmpdir)
  File "get-pip.py", line 82, in bootstrap
    import pip
  File "/tmp/tmppQTQty/pip.zip/pip/__init__.py", line 16, in <module>
  File "/tmp/tmppQTQty/pip.zip/pip/vcs/mercurial.py", line 9, in <module>
  File "/tmp/tmppQTQty/pip.zip/pip/download.py", line 39, in <module>
  File "/tmp/tmppQTQty/pip.zip/pip/_vendor/requests/__init__.py", line 61, in <module>
  File "/tmp/tmppQTQty/pip.zip/pip/_vendor/requests/packages/__init__.py", line 29, in <module>
ImportError: No module named urllib3
Run Code Online (Sandbox Code Playgroud)

当我搜索pip文件时get-pip.py,我没有看到任何对urllib3的引用.

我在机器上有python2.6,py2.7和py3.4

cchilders:~/Downloads 
$ which python
/usr/local/bin/python

cchilders:~/Downloads 
$ which pip
/usr/local/bin/pip …
Run Code Online (Sandbox Code Playgroud)

python pip python-2.x virtualenv virtualenvwrapper

8
推荐指数
1
解决办法
1万
查看次数