GVKun编程网logo

如何将onChange与react hook结合在react select上以根据用户选择更改数据库

21

本文的目的是介绍MongoDB:期望:连接失败,退出,代码为1的详细情况,特别关注mongodb连接超时的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解MongoDB

本文的目的是介绍MongoDB:期望:连接失败,退出,代码为1的详细情况,特别关注mongodb连接超时的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解MongoDB:期望:连接失败,退出,代码为1的机会,同时也不会遗漏关于Android Studio“异常:Gradle 任务组装失败,退出代码为 1”、AzerothCore MSB6006“ cmd.exe”退出,代码为1、Chutzpah 4.4.11 在使用 vstest 运行时失败,退出代码为 2、cmd:命令失败,退出代码为ENOENT的知识。

本文目录一览:

MongoDB:期望:连接失败,退出,代码为1(mongodb连接超时)

MongoDB:期望:连接失败,退出,代码为1(mongodb连接超时)

你有你去 /etc ,修改 mongod.conf,因为: “默认情况下,MongoDB 启动时 bindIp 设置为 127.0.0.1,”,它绑定到 localhost 网络接口。这意味着 mongod 只能接受来自运行在同一台机器上的客户端的连接。

然后可以 sudo nano mongod.conf 并将 127.0.0.1 更改为 0.0.0.0

您必须重新启动 mongo。

,

mongod必须先运行,然后才能运行mongo而不会出现该错误。

p.s。这是其他人从标题中偶然发现原始问题的答案

,

我也遇到了同样的错误,我认为这可能是由于PC上的某些更新(例如.NET框架更新)

然后我再次卸载并重新安装了MongoDB,它可以正常工作

,

我昨天遇到了这个问题,我能够通过以下方式解决它:

  • 删除 mongod.lock 文件。
  • 运行 config fork 命令。

删除 .lock 文件:

sudo rm /usr/local/var/mongodb/mongod.lock

运行:

mongod --config /usr/local/etc/mongod.conf --fork.

并再次使用 mongo 命令。

Android Studio“异常:Gradle 任务组装失败,退出代码为 1”

Android Studio“异常:Gradle 任务组装失败,退出代码为 1”

如何解决Android Studio“异常:Gradle 任务组装失败,退出代码为 1”?

我需要使用 Flutter 来开发一个项目,但我对 Flutter 和 Android Studio 的东西还不熟悉。打开我的虚拟 Android 设备后,我想运行代码来测试它,但我得到了异常:Gradle 任务组装失败,退出代码 1 错误。这是什么原因?当我从 CMD 运行 Flutter doctor 命令时,它没有将 Android Studio 显示为存在,可能是因为这个吗?即便如此,我还是不明白为什么还没有安装 Android Studio。如果您能提供帮助,我会很高兴。

这是我得到的错误:

enter image description here

当我运行 Flutter doctor 命令时,它显示如下:

    `C:\Users\USER>Flutter doctor
    Doctor summary (to see all details,run Flutter doctor -v):
    [√] Flutter (Channel stable,2.2.2,on Microsoft Windows [Version 10.0.19042.1052],locale tr-TR)
    [√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    [√] Chrome - develop for the web
    [!] Android Studio
        X android-studio-dir = /home/piotr/.local/share/JetBrains/ToolBox/apps/AndroidStudio/ch-0/201.6858069
        X Android Studio not found at /home/piotr/.local/share/JetBrains/ToolBox/apps/AndroidStudio/ch-0/201.6858069
    [√] VS Code (version 1.57.1)
    [√] Connected device (3 available)
    
    ! Doctor found issues in 1 category.`

解决方法

我通过安装 jdk 解决了这个错误。遇到同样错误的可以安装jdk试试。它很可能会得到解决。

AzerothCore MSB6006“ cmd.exe”退出,代码为1

AzerothCore MSB6006“ cmd.exe”退出,代码为1

从外观上看,您已经成功运行了构建,并决定单击Visual Studio上的“播放”按钮。确保您将worlserver作为启动项目。另外,由于需要多个依赖项,因此还要确保Visual Studio具有执行worldserver的正确目录。 您可以在文件所在的bin中寻找它们来手动运行这些文件。您的路径应类似于: c:\ folder_where_azerothcore_project_is \ bin \ Release

在这里,您应该已经正确配置了worldserver.conf和authserver.conf等文件以及数据库数据。您还应该有一些dll:

  • libmysql.dll
  • libcrypto-1_1-x64
  • libssl-1_1-x64

您可以在OpenSSL bin文件夹和Mysql库文件夹中找到它们。

完成所有这些配置后,尝试运行可执行文件,一切顺利!

Chutzpah 4.4.11 在使用 vstest 运行时失败,退出代码为 2

Chutzpah 4.4.11 在使用 vstest 运行时失败,退出代码为 2

如何解决Chutzpah 4.4.11 在使用 vstest 运行时失败,退出代码为 2?

vstest.console.exe 16.10 适用于 Chutzpah 4.2.3。但是升级到 Chutzpah 4.4.11,它失败了,退出代码为 2。chutzpah.console.exe 也可以在 4.4.11 中自行运行,所以我不确定我是否在 vstest 命令行中遗漏了一些东西。 (从 Azure DevOps 管道运行时,我使用 vstest.console.exe 获得了相同的结果。)

有什么建议吗?

> "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\Extensions\TestPlatform\vstest.console.exe"
 "[path-to-test-file]\index-tests.js"
 /TestAdapterPath:"C:\Users\TFSBuild\.nuget\packages\chutzpah\4.4.11\tools"
Microsoft (R) Test Execution Command Line Tool Version 16.10.0
copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution,please wait...
A total of 1 test files matched the specified pattern.
Error: UnkNown error occurred when executing test file. Received exit code of 2
While Running:[path-to-test-file]\index-tests.js

No test is available in [path-to-test-file]\index-tests.js. 
Make sure that test discoverer & executors are registered and platform & framework version settings are appropriate and try again.

Test Run Failed.

解决方法

找到了解决方案。我正在使用引擎:Chrome,而较新版本的 Chutzpah 未能找到 chrome.exe。在 Chutzpah.json 中定义 exe 的路径解决了这个问题。

  "Engine": "Chrome","EngineOptions": {
    "ChromeBrowserPath": "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
  }

cmd:命令失败,退出代码为ENOENT

cmd:命令失败,退出代码为ENOENT

嗨,我是一名初学者应用程序开发人员,我选择了phonegap,请在将android作为我的项目平台添加时查看问题。代码如下:

c:\Users\pshewale\Desktop\phone gap\hello>phonegap platform add android
npm
 http GET https://registry.npmjs.org/cordova-android

npm http 304 https://registry.npmjs.org/cordova-android

Adding android project...

Error: cmd: Command failed with exit code ENOENT
    at ChildProcess.whenDone (C:\Users\pshewale\AppData\Roaming\npm\node_modules
\phonegap\node_modules\cordova\node_modules\cordova-lib\src\cordova\superspawn.j
s:134:23)
    at ChildProcess.emit (events.js:107:17)
    at Process.ChildProcess._handle.onexit (child_process.js:1072:12)
    at child_process.js:1144:20
    at process._tickCallback (node.js:355:11)

更新:谢谢,我认为它向前移动了一点,但现在它显示了这一点:

    C:\Users\pshewale\hi>cordova platform add android
npm http GET https://registry.npmjs.org/cordova-android
npm http 200 https://registry.npmjs.org/cordova-android
npm http GET https://registry.npmjs.org/cordova-android
npm http 200 https://registry.npmjs.org/cordova-android
npm http GET https://registry.npmjs.org/cordova-android/-/cordova-android-4.0.2.
tgz
npm http 200 https://registry.npmjs.org/cordova-android/-/cordova-android-4.0.2.
tgz
Adding android project...
Error: cmd: Command failed with exit code ENOENT
    at ChildProcess.whenDone (C:\Users\pshewale\AppData\Roaming\npm\node_modules
\cordova\node_modules\cordova-lib\src\cordova\superspawn.js:134:23)
    at ChildProcess.emit (events.js:107:17)
    at Process.ChildProcess._handle.onexit (child_process.js:1072:12)
    at child_process.js:1144:20
    at process._tickCallback (node.js:355:11)

C:\Users\pshewale\hi>

我们今天的关于MongoDB:期望:连接失败,退出,代码为1mongodb连接超时的分享就到这里,谢谢您的阅读,如果想了解更多关于Android Studio“异常:Gradle 任务组装失败,退出代码为 1”、AzerothCore MSB6006“ cmd.exe”退出,代码为1、Chutzpah 4.4.11 在使用 vstest 运行时失败,退出代码为 2、cmd:命令失败,退出代码为ENOENT的相关信息,可以在本站进行搜索。

如果您对我正在使用Oauth进行Google身份验证并获取client-id和client_secret,但是显示未定义感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解我正在使用Oauth进行Google身份验证并获取client-id和client_secret,但是显示未定义的各种细节,此外还有关于android – 在使用Firebase身份验证进行身份验证后检索Google Access令牌、android – 如何使用ClientID和ClientSecret在Phonegap中使用Angularjs登录Google OAuth2、android – 新发布的“使用Google Play服务进行身份验证”,通过GoogleAuthUtil.getToken获取令牌的问题、ASP.NET OAuth授权 – 使用ClientId和Secret以及用户名和密码之间的区别的实用技巧。

本文目录一览:

我正在使用Oauth进行Google身份验证并获取client-id和client_secret,但是显示未定义

我正在使用Oauth进行Google身份验证并获取client-id和client_secret,但是显示未定义

如何解决我正在使用Oauth进行Google身份验证并获取client-id和client_secret,但是显示未定义?

在超级中,它显示错误,有人正在使用node.js来帮助解决此类型错误:

$ nodemon app.js [nodemon] 2.0.4 [nodemon]随时重新启动,请输入rs [nodemon]观看路径: [nodemon]看扩展:js,mjs,json [nodemon]开始node app.js 未定义 undefinedC:\ Users \ sunny \ desktop \ secretsstartingcode \ node_modules \ passport-oauth2 \ lib \ strategy.js:86 如果(!options.clientID){抛出新的TypeError(''OAuth2Strategy需要一个clientID选项''); } ^ TypeError:OAuth2Strategy在Strategy.OAuth2Strategy需要一个clientID选项(C:\ Users \ sunny \ desktop \ secretsstartingcode \ node_modules \ passport-oauth2 \ lib \ strategy.js:86:34) 在新策略下(C:\ Users \ sunny \ desktop \ secretsstartingcode \ node_modules \ passport-google-oauth20 \ lib \ strategy.js:52:18) 在对象。 (C:\ Users \ sunny \ desktop \ secretsstartingcode \ app.js:70:15) 在Module._compile(内部/模块/cjs/loader.js:1137:30) 在Object.Module._extensions..js(内部/模块/cjs/loader.js:1157:10) 在Module.load(internal / modules / cjs / loader.js:985:32) 在Function.Module._load(内部/模块/cjs/loader.js:878:14) 在Function.executeUserEntryPoint [作为runMain](内部/模块/run_main.js:71:12) 在internal / main / run_main_module.js:17:47 [nodemon]应用程序崩溃-等待文件更改,然后再开始...

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

android – 在使用Firebase身份验证进行身份验证后检索Google Access令牌

android – 在使用Firebase身份验证进行身份验证后检索Google Access令牌

我试图从验证的用户(使用Firebase身份验证)中检索Google Access令牌来访问Google REST API(如 YouTube Data API).

我已经在Firebase-UI for Android – Auth图书馆的帮助下,在我的应用程序中成功集成了Google登录.从FirebaseUser.getToken()方法检索的令牌不是REST API的有效Google访问令牌.

user.getToken(true).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
    public void onComplete(@NonNull Task<GetTokenResult> task) {
        if (task.isSuccessful()) {
            String token = task.getResult().getToken();
            // 'token' is not a Google Access Token
        }
    }
});

在Google Sign-In for Web guide,可以通过调用var token = result.credential.accesstoken获取访问令牌;但是我在Android中找不到类似的方法.

任何投入?如果我没有提供足够的信息,请给我留言.谢谢 :)

解决方法

你正在做的方式会给你firebase id令牌,见 here.

你会遇到三种类型的令牌,你会遇到火墙:

> Firebase ID令牌

当用户登录到Firebase应用程序时,由Firebase创建.这些令牌是签名的JWT,可以安全地识别Firebase项目中的用户.这些令牌包含用户的基本配置文件信息,包括用户的ID字符串,这是Firebase项目唯一的.由于可以验证ID令牌的完整性,因此可以将其发送到后端服务器,以识别当前登录的用户.
>身份提供者令牌

由联合身份提供商(如Google和Facebook)创建.这些令牌可以有不同的格式,但通常是OAuth 2.0访问令牌. Firebase应用程序使用这些令牌来验证用户已经使用身份提供程序成功进行身份验证,然后将其转换为Firebase服务可用的凭据.
> Firebase自定义令牌

由您的自定义验证系统创建,以允许用户使用您的验证系统登录Firebase应用.自定义令牌是使用服务帐户的私钥签名的JWT. Firebase应用程序使用这些令牌非常像使用从联合身份提供者返回的令牌.

现在,你得到的是Firebase Id令牌,你需要的是Identity Provider Token.

获取身份提供者令牌很简单,它只是您显示步骤之前的一步.

所以,我们使用firebase登录google的方式是here.

我将在下面添加完整的代码,在UI中显示一个按钮,点击后,将登录用户到谷歌帐户.然后我会得到google访问令牌,然后将其发送到firebase,在那里将其转换为firebase token Id.

我假设你已经配置Android应用程序进行谷歌登录,如果没有,你可以详细介绍here.

(为了简化,只要看下面的步骤5,如果你已经完成了设置.)

代码:

>配置Google SignIn和Googleapiclient:

// Configure sign-in to request the user's ID,email address,and basic
 // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
 GoogleSignInoptions gso = new GoogleSignInoptions.Builder(GoogleSignInoptions.DEFAULT_SIGN_IN)
    .requestIdToken(getString(R.string.default_web_client_id))
    .requestemail()
    .build();

 // NOTE : 
 // The string passed to requestIdToken,default_web_client_id,// can be obtained from credentials page (https://console.developers.google.com/apis/credentials).
 // There mentioned Web application type client ID is this string.


 // ... 
 // Build a Googleapiclient with access to the Google Sign-In API and the
 // options specified by gso.
 mGoogleapiclient = new Googleapiclient.Builder(this)
    .enableAutoManage(this /* Activity */,this /* OnConnectionFailedListener */)
    .addApi(Auth.GOOGLE_SIGN_IN_API,gso)
    .build();

>将Google登录按钮添加到您的应用程序

<com.google.android.gms.common.SignInButton
    android:id="@+id/sign_in_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

>设置SignIn Click Listener

findViewById(R.id.sign_in_button).setonClickListener(new OnClickListener() {
    public void onClick(View v){
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleapiclient);
        startActivityForResult(signInIntent,RC_SIGN_IN);   
    }
});

>覆盖活动中的OnActivityResult方法:

@Override
public void onActivityResult(int requestCode,int resultCode,Intent data) {
    super.onActivityResult(requestCode,resultCode,data);

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        // Google Sign In was successful,authenticate with Firebase
        GoogleSignInAccount account = result.getSignInAccount();
        firebaseAuthWithGoogle(account); // This method is implemented in step 5.
    } else {
        // Google Sign In Failed,update UI appropriately
        // ...
    }
}

>使用Google SignInAccount进行Firebase验证

String idTokenString = "";
...
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG,"Google User Id :" + acct.getId());

    // --------------------------------- //
    // BELOW LINE GIVES YOU JSON WEB TOKEN,(USED TO GET ACCESS TOKEN) : 
    Log.d(TAG,"Google JWT : " + acct.getIdToken());
    // --------------------------------- //

    // Save this JWT in global String : 
    idTokenString = acct.getIdToken();

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);
    mAuth.signInWithCredential(credential)
        .addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                Log.d(TAG,"signInWithCredential:onComplete:" + task.isSuccessful());

                if(task.isSuccessful()){
                    // --------------------------------- //
                    // BELOW LINE GIVES YOU FIREBASE TOKEN ID : 
                    Log.d(TAG,"Firebase User Access Token : " + task.getResult().getToken());
                    // --------------------------------- //
                }
                // If sign in fails,display a message to the user. If sign in succeeds
                // the auth state listener will be notified and logic to handle the
                // signed in user can be handled in the listener.
                else {
                    Log.w(TAG,"signInWithCredential",task.getException());
                    Toast.makeText(GoogleSignInActivity.this,"Authentication Failed.",Toast.LENGTH_SHORT).show();
                }
            }
        });
}

>最后一步:Firebase的认证听众

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // ...
    mAuth = FirebaseAuth.getInstance();
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG,"onAuthStateChanged:signed_in:" + user.getUid());
            } else {
               // User is signed out
               Log.d(TAG,"onAuthStateChanged:signed_out");
            }
            // ...
        }
   };
   // ...
}

//...

@Override
public void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}

@Override
public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

所以,你的答案在于第5步,这是在您验证firebase之前,并在您的身份验证后,谷歌登录.

希望有帮助!

更新:

重要的是,在步骤1中,您请求令牌ID,否则在步骤5中,您将获得空标记ID.有关更多信息,请参阅here.我已更新步骤1.

更新:

根据讨论,检索的令牌是写入here的JWT令牌.我们需要的是谷歌访问令牌.以下代码使用JWT令牌在OAuth后端启动并检索此访问令牌:

(注:我已经使用okhttp版本2.6.0,其他版本可能有不同的方法)

代码:

...
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new FormEncodingBuilder()
            .add("grant_type","authorization_code")
            .add("client_id","<Your-client-id>")   // something like : ...apps.googleusercontent.com
            .add("client_secret","{Your-client-secret}")
            .add("redirect_uri","")
            .add("code","4/4-GMMhmHCXhWEzkobqIHGG_EnNYYsAkukHspeYUk9E8") // device code.
            .add("id_token",idTokenString) // This is what we received in Step 5,the jwt token.
            .build();

final Request request = new Request.Builder()
        .url("https://www.googleapis.com/oauth2/v4/token")
        .post(requestBody)
        .build();

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(final Request request,final IOException e) {
        Log.e(LOG_TAG,e.toString());                
    }

    @Override
    public void onResponse(Response response) throws IOException {
        try {
            JSONObject jsonObject = new JSONObject(response.body().string());
            final String message = jsonObject.toString(5);
            Log.i(LOG_TAG,message);                    
        } catch (JSONException e) {
            e.printstacktrace();
        }
    }
});

这是根据需要具有访问令牌的输出:

I/OnResponse: {
          "expires_in": 3600,"token_type": "Bearer","refresh_token": "1\/xz1eb0XU3....nxoALEVQ","id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjQxMWY1Ym......yWVsUA","access_token": "ya29.bQKKYah-........_tkt980_qAGIo9yeWEG4"
     }

希望现在有帮助!

android – 如何使用ClientID和ClientSecret在Phonegap中使用Angularjs登录Google OAuth2

android – 如何使用ClientID和ClientSecret在Phonegap中使用Angularjs登录Google OAuth2

我正尝试使用 Angularjs(使用Ionic Framework)通过Google OAuth2从我的Phonegap应用程序登录.目前我正在使用 http://phonegap-tips.com/articles/google-api-oauth-with-phonegaps-inappbrowser.html进行登录.但是当我使用Angular-UI-Router for Ionic时,它正在创建非常难看的代码和相当难以理解的代码.

如果没有任何正确的答案,这个问题似乎正在蔓延.我希望现在应该解决. Google Angular Guys应该会有所帮助.
How to implement Google Auth in phonegap?

最接近的主题是How to use Google Login API with Cordova/Phonegap,但这不是angularjs的解决方案.

我不得不使用以下代码传输javascript变量值:

var el = document.getElementById('test');
        var scopeTest = angular.element(el).scope();
        scopeTest.$apply(function(){ 
            scopeTest.user = user;
            scopeTest.logged_in = true;
            scopeTest.name = user.name;
            scopeTest.email = user.email;
        });

解决方法

我做了这样的解决方案,其中TestCtrl是Login Button所在的Controller.有一个基于jquery的$.ajax调用混合,我将改变为angualar方式. google_call函数基本上调用google_api,这在上面提到的phonegap-tips中提到的链接中提到.
.controller('TestCtrl',function($scope,$ionicPopup) {
$scope.logged_in = false;
$scope.getMember = function(id) {
    console.log(id);
};
$scope.test = function(){
    $ionicPopup.alert({"title":"Clicked"});
}

$scope.call_google = function(){
    googleapi.authorize({
    client_id: 'CLIENT_ID',client_secret: 'CLIENT_SECRET',redirect_uri: 'http://localhost',scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
    }).done(function(data) {
        accesstoken=data.access_token;
        // alert(accesstoken);
        // $loginStatus.html('Access Token: ' + data.access_token);
        console.log(data.access_token);
        //$ionicPopup.alert({"title":JSON.stringify(data)});
        $scope.getDataProfile();
    });
};
$scope.getDataProfile = function(){
    var term=null;
    //  alert("getting user data="+accesstoken);
    $.ajax({
           url:'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='+accesstoken,type:'GET',data:term,dataType:'json',error:function(jqXHR,text_status,strError){
           },success:function(data)
           {
           var item;

           console.log(JSON.stringify(data));
           // Save the userprofile data in your localStorage.
           window.localStorage.gmailLogin="true";
           window.localStorage.gmailID=data.id;
           window.localStorage.gmailEmail=data.email;
           window.localStorage.gmailFirstName=data.given_name;
           window.localStorage.gmailLastName=data.family_name;
           window.localStorage.gmailProfilePicture=data.picture;
           window.localStorage.gmailGender=data.gender;
           window.localStorage.gmailName=data.name;
           $scope.email = data.email;
           $scope.name = data.name;
           }
        });
        //$scope.disconnectUser(); //This call can be done later.
};
$scope.disconnectUser = function() {
  var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token='+accesstoken;

  // Perform an asynchronous GET request.
  $.ajax({
    type: 'GET',url: revokeUrl,async: false,contentType: "application/json",dataType: 'jsonp',success: function(nullResponse) {
      // Do something Now that user is disconnected
      // The response is always undefined.
      accesstoken=null;
      console.log(JSON.stringify(nullResponse));
      console.log("-----signed out..!!----"+accesstoken);
    },error: function(e) {
      // Handle the error
      // console.log(e);
      // You Could point users to manually disconnect if unsuccessful
      // https://plus.google.com/apps
    }
  });
};
})

我正在为尝试使用Google OAuth2登录时面临类似问题的新手提供此答案.因此,我无耻地要求UpVotes,因为我也是新来的!

android – 新发布的“使用Google Play服务进行身份验证”,通过GoogleAuthUtil.getToken获取令牌的问题

android – 新发布的“使用Google Play服务进行身份验证”,通过GoogleAuthUtil.getToken获取令牌的问题

更新:

刚刚通过我也用于Google App Engine的Google帐户注册了Google Api,现在错误已更改为com.google.android.gms.auth.GoogleAuthException:未知

谷歌刚刚发布了一个新的方式到sign up to one’s app via a Google Account,并在他们的blogpost也给了一些解释.

我正在编写一个Android应用程序,您必须注册才能创建一个用户帐户,并且我在后端使用Google App Engine.通过播放服务,我想让用户的电子邮件附属于他们的Android设备和令牌.我可以收到电子邮件,但是,获取令牌只会引发错误,由于文档相当稀疏,我不知道如何解决这些错误.这就是我收到的电子邮件:

private String[] getAccountNames() {
    mAccountManager = AccountManager.get(this);
    Account[] accounts = mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
    names = new String[accounts.length];
    for (int i = 0; i < names.length; i++) {
        names[i] = accounts[i].name;
    }

    return names;
}

但是,当我打电话给token = GoogleAuthUtil.getToken(上下文,电子邮件,
“范围”,它给我这些错误:
由于错误1和com.google.android.gms.auth.GooglePlayServicesAvailabilityException:GooglePlayServicesNotAvailable,GooglePlayServices不可用.

现在我的问题是,我必须设置任何权限或包含任何库来解决这个问题吗?什么是范围参数?在他们的博客文章中给出了如何获取令牌和放置在范围内的示例,将范围变量设置为“https://www.googleapis.com/auth/userinfo.profile”,但是我仍然收到相同的错误不幸.

我还注册了我的Google Api控制台应用程序并启用了G API,是否还必须配置其他的东西?

解决方法

使用Google云端硬盘的Google客户端库时,我遇到了同样的问题.
解决方案很简单.只需将“oauth2:”添加到您的scopeUrl.

错误:

GoogleAuthUtil.getToken(this,account.name,DriveScopes.DRIVE);

对:

GoogleAuthUtil.getToken(this,"oauth2:" + DriveScopes.DRIVE);

ASP.NET OAuth授权 – 使用ClientId和Secret以及用户名和密码之间的区别

ASP.NET OAuth授权 – 使用ClientId和Secret以及用户名和密码之间的区别

我正在尝试在ASP.NET WebAPI 2中实现一个简单的OAuthAuthorizationServerProvider.我的主要目的是学习如何为移动应用程序设置令牌.我希望用户使用用户名&密码,然后接收令牌(和刷新令牌,这样一旦令牌过期,他们就不必重新输入凭据).稍后,我希望有机会打开其他应用程序外部使用的API(比如使用Facebook api等……).

以下是我设置AuthorizationServer的方法:

app.USEOAuthAuthorizationServer(new OAuthAuthorizationServerOptions()
{
    AllowInsecureHttp = true,TokenEndpointPath = new PathString("/token"),AccesstokenExpireTimeSpan = TimeSpan.FromMinutes(5),Provider = new SimpleAuthorizationServerProvider(new SimpleAuthorizationServerProviderOptions()
    {
        ValidateUserCredentialsFunction = ValidateUser
    }),RefreshTokenProvider = new SimpleRefreshTokenProvider()
});

这是我的SimpleAuthorizationServerProviderOptions实现:

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public delegate Task<bool> ClientCredentialsValidationFunction(string clientid,string secret);
    public delegate Task<IEnumerable<Claim>> UserCredentialValidationFunction(string username,string password);
    public SimpleAuthorizationServerProviderOptions Options { get; private set; }

    public SimpleAuthorizationServerProvider(SimpleAuthorizationServerProviderOptions options)
    {
        if (options.ValidateUserCredentialsFunction == null)
        {
            throw new NullReferenceException("ValidateUserCredentialsFunction cannot be null");
        }
        Options = options;
    }

    public SimpleAuthorizationServerProvider(UserCredentialValidationFunction userCredentialValidationFunction)
    {
        Options = new SimpleAuthorizationServerProviderOptions()
        {
            ValidateUserCredentialsFunction = userCredentialValidationFunction
        };
    }

    public SimpleAuthorizationServerProvider(UserCredentialValidationFunction userCredentialValidationFunction,ClientCredentialsValidationFunction clientCredentialsValidationFunction)
    {
        Options = new SimpleAuthorizationServerProviderOptions()
        {
            ValidateUserCredentialsFunction = userCredentialValidationFunction,ValidateClientCredentialsFunction = clientCredentialsValidationFunction
        };
    }

    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        if (Options.ValidateClientCredentialsFunction != null)
        {
            string clientId,clientSecret;

            if (!context.TryGetBasicCredentials(out clientId,out clientSecret))
            {
                context.TryGetFormCredentials(out clientId,out clientSecret);
            }

            var clientValidated = await Options.ValidateClientCredentialsFunction(clientId,clientSecret);
            if (!clientValidated)
            {
                context.Rejected();
                return;
            }
        }

        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        if (Options.ValidateUserCredentialsFunction == null)
        {
            throw new NullReferenceException("ValidateUserCredentialsFunction cannot be null");
        }

        var claims = await Options.ValidateUserCredentialsFunction(context.UserName,context.Password);
        if (claims == null)
        {
            context.Rejected();
            return;
        }

        // create identity
        var identity = new ClaimsIdentity(claims,context.Options.AuthenticationType);

        // create Metadata to pass to refresh token provider
        var props = new AuthenticationProperties(new Dictionary<string,string>()
        {
            { "as:client_id",context.UserName }
        });

        var ticket = new AuthenticationTicket(identity,props);
        context.Validated(ticket);
    }

    public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
    {
        var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
        var currentClient = context.ClientId;

        // enforce client binding of refresh token
        if (originalClient != currentClient)
        {
            context.Rejected();
            return;
        }

        // chance to change authentication ticket for refresh token requests
        var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
        newIdentity.AddClaim(new Claim("newClaim","refreshToken"));

        var newTicket = new AuthenticationTicket(newIdentity,context.Ticket.Properties);
        context.Validated(newTicket);
    }
}

我的SimpleRefreshTokenProvider实现:

public class SimpleRefreshTokenProvider : IAuthenticationTokenProvider
{
    private static ConcurrentDictionary<string,AuthenticationTicket> _refreshTokens =
        new ConcurrentDictionary<string,AuthenticationTicket>(); 

    public void Create(AuthenticationTokenCreateContext context)
    {

    }

    public async Task CreateAsync(AuthenticationTokenCreateContext context)
    {
        var guid = Guid.NewGuid().ToString();

        var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
        {
            IssuedUtc = context.Ticket.Properties.IssuedUtc,ExpiresUtc = DateTime.UtcNow.AddYears(1)
        };
        var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity,refreshTokenProperties);

        _refreshTokens.TryAdd(guid,refreshTokenTicket);
        context.SetToken(guid);
    }

    public void Receive(AuthenticationTokenReceiveContext context)
    {

    }

    public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {
        AuthenticationTicket ticket;
        if (_refreshTokens.TryRemove(context.Token,out ticket))
        {
            context.SetTicket(ticket);
        }
    }
}

我不完全理解的是使用ClientId和Secret vs用户名和密码.我粘贴的代码通过用户名和密码生成令牌,我可以使用该令牌(直到它过期),但是当我尝试获取刷新令牌时,我必须拥有ClientId.

此外,如果令牌过期,正确的方法是发送刷新令牌并获取新令牌?如果刷新令牌被盗怎么办?是不是用户名和&密码被盗?

解决方法

What I don’t fully understand is the use of ClientId and Secret vs Username and Password. The code I pasted generates a token by username and password and I can work with that token (until it expires),but when I try to get a refresh token,I must have the ClientId.

Also,if a token expires,the correct way is to send the refresh token and get a new token? What if the refresh token gets stolen? isn’t it the same as a username & password getting stolen?

在OAuth2中,必须在协议定义的任何授权流中对用户和客户端进行身份验证.客户端身份验证(您可能猜到)仅强制使用您的API,只有已知客户端才能使用.序列化访问令牌一旦生成,就不会直接绑定到特定客户端.请注意,ClientSecret必须被视为机密信息,并且只能由能够以某种安全方式存储此信息的客户端使用(例如,外部服务客户端,而不是javascript客户端).

刷新令牌只是OAuth2的替代“授权类型”,并且正如您所说的那样,将替换用户的用户名和密码对.此令牌必须被视为机密数据(甚至比访问令牌更加机密),但优于存储用户名和密码.客户端密码:

>如果受到损害,用户可以撤销;
>它的寿命有限(通常是几天或几周);
>它不会公开用户凭据(攻击者只能获取发布刷新令牌的“范围”的访问令牌).

我建议您阅读有关official draft中OAuth 2检查中定义的不同授权类型的更多信息.我还建议您this resource我发现在Web API中首次实现OAuth2时非常有用.

样品申请

以下是使用fiddler的两个请求示例,用于资源所有者密码凭据授予:

和刷新令牌授予:

我们今天的关于我正在使用Oauth进行Google身份验证并获取client-id和client_secret,但是显示未定义的分享就到这里,谢谢您的阅读,如果想了解更多关于android – 在使用Firebase身份验证进行身份验证后检索Google Access令牌、android – 如何使用ClientID和ClientSecret在Phonegap中使用Angularjs登录Google OAuth2、android – 新发布的“使用Google Play服务进行身份验证”,通过GoogleAuthUtil.getToken获取令牌的问题、ASP.NET OAuth授权 – 使用ClientId和Secret以及用户名和密码之间的区别的相关信息,可以在本站进行搜索。

如果您想了解为什么mongoimport.exe从我的程序包中消失了?mongoimport 没找到的知识,那么本篇文章将是您的不二之选。我们将深入剖析为什么mongoimport.exe从我的程序包中消失了?的各个方面,并为您解答mongoimport 没找到的疑在这篇文章中,我们将为您介绍为什么mongoimport.exe从我的程序包中消失了?的相关知识,同时也会详细的解释mongoimport 没找到的运用方法,并给出实际的案例分析,希望能帮助到您!

本文目录一览:

为什么mongoimport.exe从我的程序包中消失了?(mongoimport 没找到)

为什么mongoimport.exe从我的程序包中消失了?(mongoimport 没找到)

我遇到了同样的问题。请查找以下信息可能会帮助您解决与 mongoimport 相关的问题。

从 MongoDB 4.4 服务器版本开始,数据库工具现在单独进行版本控制和安装。这些工具独立于 MongoDB 服务器计划发布,使您能够接收更频繁的更新并在新功能可用时立即利用它们。其中包括:mongodump、mongorestore、mongoimport 和 mongoexport。

This is the download link for MongoDB Database Tools

,

我自己也遇到了同样的问题。从MongoDB 4.4开始,数据库工具现在是Linux以外所有平台的单独安装。您可以找到针对平台here安装的说明。

"from pymongo import Connection" (to import mongo.connection using python) , got "500 Internal Server Error"

I created the /var/www/cgi-bin/test.py in my web server machine (Linux). The service of mongoDB "mongod" is running.

When I run the test.py locally, "./test.py", I could get the correct result.

But when I use the URL: http://xxxxxx.compute-1.amazonaws.com/cgi-bin/python_test/test.py to run the test.py, I will get the "500 Internal Server Error". 

If I remove the line "from pymongo import Connection", and use the URL above to access, I won''t get the 500 Internal server error. So, it should be the problem when I import the pymongo.connection.

Is it the problem of any configuration issue? Thanks so much for your help

========== test.py ==============

#!/usr/bin/python
import cgi
import sys
sys.path.append("/home/ec2-user/mongo-python-driver-2.6.3/")

#import pymongo.connection
from pymongo import Connection
def main():
        print "Content-type: text/html\r\n\r\n"
        form = cgi.FieldStorage()
        name = form.getvalue(''ServiceCode'')
#       name = "abcddd"
#       con = Connection()
#       db = con.test
#       posts = db.post

#       print name
        if form.has_key("ServiceCode") and form["ServiceCode"].value!="":
                print"<h1>Hello", form["ServiceCode"].value,"</h1>"
        else:
                print"<h1>Error! Please enter first name. </h1>"

 .....


2,使用mongoimport批量导入数据

2,使用mongoimport批量导入数据

1,下载MongoDB数据库工具

https://www.mongodb.com/try/download/database-tools

注意:
	从MongoDB 4.4开始,MongoDB数据库工具单独发布,使用自己的版本,初始版本为100.0.0
	
	目前最新的版本为100.3.1,其支持如下版本:
	MongoDB 5.0
	MongoDB 4.4
	MongoDB 4.2
	MongoDB 4.0
	MongoDB 3.6

2,安装

1,可以下载.msi或zip包
2,如果是zip,需要解压到某个目录,并将其配置到系统环境变量里面

3,启动mongo服务

mongod.exe --dbpath D:\UserData\mongodb --auth

4,批量导入数据

cd D:\DevelopmentTool\mongodb-win32-x86_64-windows-5.0.0\tool
mongoimport --db test --collection book --authenticationDatabase admin --username admin --password 123456 --drop --file D:\UserData\Administrator\Desktop\book.crud.json

说明:
	--db test 将数据存入test库
	--collection book 将数据存入book集合
	--authenticationDatabase admin --username admin --password 123456  使用admin和123456进行登录
	--drop 如果集合存在,就删除
	--file D:\UserData\Administrator\Desktop\book.crud.json 指定导入的数据文件
	
文件book.crud.json内容:
{ "item": "journal", "qty": 25, "size": { "h": 14, "w": 21, "uom": "cm" }, "status": "A" }
{ "item": "notebook", "qty": 50, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "A" }
{ "item": "paper", "qty": 100, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "D" }
{ "item": "planner", "qty": 75, "size": { "h": 22.85, "w": 30, "uom": "cm" }, "status": "D" }
{ "item": "postcard", "qty": 45, "size": { "h": 10, "w": 15.25, "uom": "cm" }, "status": "A" }
	
# 输出
2021-07-15T09:17:12.084+0800    connected to: mongodb://localhost/
2021-07-15T09:17:12.160+0800    dropping: test.book
2021-07-15T09:17:12.641+0800    5 document(s) imported successfully. 0 document(s) failed to import.

# 查询所有数据
# 连接服务端
..\bin\mongo.exe mongodb://admin:123456@127.0.0.1:27017/admin
# 切换数据库
use test;
# 查询所有数据
books = db.book.find({});

android-为什么imageview在布局上消失了?

android-为什么imageview在布局上消失了?

imageview在布局的右侧.如果messagedetail_row_text的内容太长,则不会显示.如果messagedetail_row_text的内容不太长,则会显示imageview.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="15dp"
    android:gravity="right"
    android:orientation="horizontal" >

    <LinearLayout
        android:id="@+id/dfdwasdfds"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/outgoing"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="22dip"
            android:orientation="horizontal" >

            <TextView
                android:id="@+id/messagedetail_row_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingTop="1dp"
                android:textColor="#000000"
                android:textSize="18sp" />

            <TextView
                android:id="@+id/messagedetail_row_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dip"
                android:paddingTop="1dp"
                android:textColor="#000000"
                android:textSize="16sp" />
        </LinearLayout>

        <TextView
            android:id="@+id/messagedetail_row_text"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="2dp"
            android:textColor="#000000"
            android:textSize="20sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" 
        android:layout_toRightOf="@id/dfdwasdfds"
        >

        <ImageView
            android:id="@+id/messagegedetail_rov_icon2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:gravity="right"
            android:src="@drawable/retouxiang" />

    </LinearLayout>

</RelativeLayout>

解决方法:

不清楚您要寻找的是什么.据我了解:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="15dp"
    android:gravity="right"
    android:orientation="horizontal" >

    <LinearLayout
        android:id="@+id/xyz"
        android:layout_alignParentRight="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" 
        >

        <ImageView
            android:id="@+id/messagegedetail_rov_icon2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:gravity="right"
            android:src="@drawable/retouxiang" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/dfdwasdfds"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/xyz"
        android:background="@drawable/outgoing"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="22dip"
            android:orientation="horizontal" >

            <TextView
                android:id="@+id/messagedetail_row_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingTop="1dp"
                android:textColor="#000000"
                android:text="messagedetail_row_name"
                android:textSize="18sp" />

            <TextView
                android:id="@+id/messagedetail_row_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dip"
                android:paddingTop="1dp"
                android:text="messagedetail_row_date"
                android:textColor="#000000"
                android:textSize="16sp" />
        </LinearLayout>

        <TextView
            android:id="@+id/messagedetail_row_text"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="2dp"
            android:text="messagedetail_row_text and this is a long text"
            android:textColor="#000000"
            android:textSize="20sp" />
    </LinearLayout>

</RelativeLayout>

ios – 为什么我的Xcode 6.1.1模拟器选项都消失了?

ios – 为什么我的Xcode 6.1.1模拟器选项都消失了?

我最近尝试在访问印度尼西亚期间使用我的MacBook Pro在 Xcode 6.1.1上运行新的iOS 7应用程序模拟.该应用程序基于AddMusic并使iOS 7兼容.当我试图在国外运行模拟器时,在澳大利亚测试时可用的iOS模拟目标已经从Xcode的下拉菜单中消失了.此外,自从我回到家后,这些模拟器仅在我移除,下载并重新安装Xcode时才重新出现.

在我重新安装Xcode之前,Xcode提供的唯一选择是在iOS设备上运行应用程序,但我没有准备在客户面前执行此操作,而无需先在模拟器上测试修订版本.

值得庆幸的是,在我离开家之前,我能够演示我在iPhone 4和iPhone 5 C上安装的早期版本.但是,在我下次出国访问期间,了解我可以做些什么来避免这种情况真的很好.

我怀疑这个问题可能是由我国内外的互联网连接之间的差异引起的.

有没有其他人遇到过可能相关的类似问题?

解决方法

在你的右边点击
窗口>设备

您将看到没有设备显示请执行以下操作左下方点击然后开始添加您的设备.

今天关于为什么mongoimport.exe从我的程序包中消失了?mongoimport 没找到的介绍到此结束,谢谢您的阅读,有关"from pymongo import Connection" (to import mongo.connection using python) , got "500 Internal Server Error"、2,使用mongoimport批量导入数据、android-为什么imageview在布局上消失了?、ios – 为什么我的Xcode 6.1.1模拟器选项都消失了?等更多相关知识的信息可以在本站进行查询。

在本文中,我们将给您介绍关于如何编辑Prestashop后台客户获取数据的详细内容,并且为您解答prestashop教程的相关问题,此外,我们还将为您提供关于ecshop后台登录后出现了xmlHttpRequest status:[500] Unknow status.这个是什么错误啊!、ecshop后台编辑器替换成ueditor编辑器、ecshop后台编辑器替换成ueditor编辑器_PHP、ecshop后台编辑器替换成ueditor编辑器_php实例的知识。

本文目录一览:

如何编辑Prestashop后台客户获取数据(prestashop教程)

如何编辑Prestashop后台客户获取数据(prestashop教程)

如何解决如何编辑Prestashop后台客户获取数据?

我已经创建了一个用户级别“卖方”,我希望这种类型的每个用户只能看到分配给他的订单和客户。我在ps_customer表中添加了一个列,以将客户与卖方相关联。对于我已成功完成的订单(用户以卖方身份登录,他只看到分配给他的客户的订单),而在后台中找不到管理“客户”部分的控制器。

谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

ecshop后台登录后出现了xmlHttpRequest status:[500] Unknow status.这个是什么错误啊!

ecshop后台登录后出现了xmlHttpRequest status:[500] Unknow status.这个是什么错误啊!

ecshop后台登录后出现了xmlHttpRequest status:[500] Unknow status.这个是什么错误啊!求解决 !!!

ecshop后台编辑器替换成ueditor编辑器

ecshop后台编辑器替换成ueditor编辑器

1、Ueditor1.4.3下载

(截止到2015-03-03最新版)

下载地址: 解决jquery冲突的jquery等相关文件下载 文件中已含js冲突修改文件,另外已修改php/config.json中的图处保存路径,用户也可以自行修改! 因为老杨用的是mac os系统,所以文件中有一些.DS_store文件,可以忽略或自行删除 下载地址: 密码:fflu (老杨提供)

2、上传到网站服务器

解压并上传目录 uediter 到根目录 /includes 下 解压老杨的那个东东,把fix_jquery上传到 ueditor 的目录下

3、修改/admin/includes/lib_main.PHP

找到下面的函数

代码如下:
$editor = new FCKeditor($input_name);
$editor->BasePath = '../includes/fckeditor/';
$editor->ToolbarSet = 'normal';
$editor->Width = '100%';
$editor->Height = '320';
$editor->Value = $input_value;
$FCKeditor = $editor->CreateHtml();
$smarty->assign('FCKeditor',$FCKeditor);
}

替换为:

代码如下:
生成编辑器 * @param string input_name 输入框名称 * @param string input_value 输入框值 */ function create_html_editor($input_name,$input_value = '') { global $smarty; $kindeditor=" "; $smarty->assign('FCKeditor',$kindeditor); }

4、修改/admin/templates/pageheader.htm

查找:

代码如下:

替换为:

代码如下:总结

以上是小编为你收集整理的ecshop后台编辑器替换成ueditor编辑器全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

ecshopecshopueditor编辑器编辑器编辑器

ecshop后台编辑器替换成ueditor编辑器_PHP

ecshop后台编辑器替换成ueditor编辑器_PHP

1、Ueditor1.4.3下载(截止到2015-03-03最新版)

下载地址:http://ueditor.baidu.com/website/download.html
解决jquery冲突的jquery等相关文件下载
文件中已含js冲突修改文件,另外已修改php/config.json中的图处保存路径,用户也可以自行修改!
因为老杨用的是mac os系统,所以文件中有一些.DS_store文件,可以忽略或自行删除
下载地址:http://pan.baidu.com/s/1gdglb0J 密码:fflu (老杨提供)

2、上传到网站服务器

解压并上传目录 uediter 到根目录 /includes 下
解压老杨的那个东东,把fix_jquery上传到 ueditor 的目录下

3、修改/admin/includes/lib_main.php

找到下面的函数

代码如下:

立即学习“PHP免费学习笔记(深入)”;


/**
 * 生成编辑器
 * @param   string  input_name  输入框名称
 * @param   string  input_value 输入框值
 */ 
function create_html_editor($input_name, $input_value = '''') 

    global $smarty; 
  
    $editor = new FCKeditor($input_name); 
    $editor->BasePath   = ''../includes/fckeditor/''; 
    $editor->ToolbarSet = ''Normal''; 
    $editor->Width      = ''100%''; 
    $editor->Height     = ''320''; 
    $editor->Value      = $input_value; 
    $FCKeditor = $editor->CreateHtml(); 
    $smarty->assign(''FCKeditor'', $FCKeditor); 
}

替换为:

代码如下:

立即学习“PHP免费学习笔记(深入)”;


/**
 * 生成编辑器
 * @param   string  input_name  输入框名称
 * @param   string  input_value 输入框值
 */
function create_html_editor($input_name, $input_value = '''')
{
    global $smarty;
    $kindeditor="
   
   
   
    <script><br /> var ue = UE.getEditor(''editor'');<br /> </script>
    ";
    $smarty->assign(''FCKeditor'', $kindeditor);
}

4、修改/admin/templates/pageheader.htm

查找:

代码如下:

立即学习“PHP免费学习笔记(深入)”;


{insert_scripts files="../js/transport.js,common.js,../js/utils.js"}

替换为:

代码如下:

立即学习“PHP免费学习笔记(深入)”;






{insert_scripts files="../js/utils.js"}

5、解决商品编辑中编辑器被重置,uedite无法保存内容的bug。

文件:/admin/templates/goods_info.htm
找到:

代码如下:

立即学习“PHP免费学习笔记(深入)”;


document.forms[''theForm''].reset();

注释掉:

代码如下:

立即学习“PHP免费学习笔记(深入)”;


//document.forms[''theForm''].reset();

以上所述就是本文的全部内容了,希望大家能够喜欢。

ecshop后台编辑器替换成ueditor编辑器_php实例

ecshop后台编辑器替换成ueditor编辑器_php实例

1、Ueditor1.4.3下载(截止到2015-03-03最新版)

下载地址:http://ueditor.baidu.com/website/download.html
解决jquery冲突的jquery等相关文件下载
文件中已含js冲突修改文件,另外已修改php/config.json中的图处保存路径,用户也可以自行修改!
因为老杨用的是mac os系统,所以文件中有一些.DS_store文件,可以忽略或自行删除
下载地址:http://pan.baidu.com/s/1gdglb0J 密码:fflu (老杨提供)

2、上传到网站服务器

解压并上传目录 uediter 到根目录 /includes 下
解压老杨的那个东东,把fix_jquery上传到 ueditor 的目录下

3、修改/admin/includes/lib_main.php

找到下面的函数

复制代码 代码如下:

/**
 * 生成编辑器
 * @param   string  input_name  输入框名称
 * @param   string  input_value 输入框值
 */ 
function create_html_editor($input_name, $input_value = '''') 

    global $smarty; 
  
    $editor = new FCKeditor($input_name); 
    $editor->BasePath   = ''../includes/fckeditor/''; 
    $editor->ToolbarSet = ''Normal''; 
    $editor->Width      = ''100%''; 
    $editor->Height     = ''320''; 
    $editor->Value      = $input_value; 
    $FCKeditor = $editor->CreateHtml(); 
    $smarty->assign(''FCKeditor'', $FCKeditor); 
}

替换为:

复制代码 代码如下:

/**
 * 生成编辑器
 * @param   string  input_name  输入框名称
 * @param   string  input_value 输入框值
 */
function create_html_editor($input_name, $input_value = '''')
{
    global $smarty;
    $kindeditor="
   
   
   
    <script><br /> var ue = UE.getEditor(''editor'');<br /> </script>
    ";
    $smarty->assign(''FCKeditor'', $kindeditor);
}

4、修改/admin/templates/pageheader.htm

查找:

立即学习“PHP免费学习笔记(深入)”;

复制代码 代码如下:

{insert_scripts files="../js/transport.js,common.js,../js/utils.js"}

替换为:

复制代码 代码如下:





{insert_scripts files="../js/utils.js"}

5、解决商品编辑中编辑器被重置,uedite无法保存内容的bug。

文件:/admin/templates/goods_info.htm
找到:

复制代码 代码如下:

document.forms[''theForm''].reset();

注释掉:

复制代码 代码如下:

//document.forms[''theForm''].reset();

以上所述就是本文的全部内容了,希望大家能够喜欢。

今天的关于如何编辑Prestashop后台客户获取数据prestashop教程的分享已经结束,谢谢您的关注,如果想了解更多关于ecshop后台登录后出现了xmlHttpRequest status:[500] Unknow status.这个是什么错误啊!、ecshop后台编辑器替换成ueditor编辑器、ecshop后台编辑器替换成ueditor编辑器_PHP、ecshop后台编辑器替换成ueditor编辑器_php实例的相关知识,请在本站进行查询。

针对Python-线程-如何创建播放列表函数以在后台通过线程运行?python 创建线程这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展android – 如何创建播放列表、c# – 如果异步方法是单线程的,它怎么能在后台运行?、c# 线程池:开启10个线程运行Fibonacci,并在所有线程运行完后,得出结果。、ios – complition处理程序关闭是否总是在后台线程运行?等相关知识,希望可以帮助到你。

本文目录一览:

Python-线程-如何创建播放列表函数以在后台通过线程运行?(python 创建线程)

Python-线程-如何创建播放列表函数以在后台通过线程运行?(python 创建线程)

尝试将Thread(target=playPlaylist,args=(playlist)).start()更改为Thread(target=playPlaylist,args=(playlist,)).start()对我而言很有帮助。还要检查代码中调用函数的所有元素(如果它们不是字符串)。如果这样做不起作用,请与Mixer类共享文件,以便我进一步帮助您。

,

args参数应该是iterable(例如元组或列表),其中每个元素都成为函数playPlayList的参数。指定args=(playlist)时,playlist周围的括号不表示一个元素的元组。为此,您需要指定args=(playlist,)。因此,playlist本身被解释为可迭代的,并且其每个元素将被视为playPlayList的单独参数。 playlist中目前只能有一个元素,例如,如果有3个元素,则会显示错误消息,例如:

TypeError: playPlaylist() takes 1 positional argument but 3 were given

因此,您需要指定:args=(playlist,)。那是第一个问题。

由于不再传递playlist,而是传递该列表的第一个也是唯一的元素作为参数,因此可能导致第二个错误。但我认为您会在以下位置得到例外:

for music in playlist:

但是playlist的第一个元素本身就是可迭代的。不过,请尝试解决第一个问题,然后看看会发生什么。

android – 如何创建播放列表

android – 如何创建播放列表

我正在尝试创建一个只提供edittext和imagebutton的应用程序.如果点击了按钮,则想法是将相册添加到播放列表中,在edittext框中命名.相册应随机选择.不言而喻,专辑曲目应该是正确的顺序.
我可以稍后添加更多功能,例如.保存,覆盖,删除等
我有界面,但我正在努力与代码.我有点得到ContentProviders的概念.
所以代码需要:

>访问播放列表,我相信这是通过使用MediaStore.Audio.Playlists实现的
>访问相册,我相信这是通过使用MediaStore.Audio.Albums实现的
>添加到播放列表

我有以下代码(从该站点获得的大多数位.感谢btw)访问播放列表但它崩溃时出现Null Exception错误.

public void checkforplaylists()
{
    //Get a cursor over all playlists.
    final ContentResolver resolver= MediaProvider.mContentResolver;
    final Uri uri=MediaStore.Audio.Playlists.INTERNAL_CONTENT_URI;
    final String id=MediaStore.Audio.Playlists._ID;
    final String name=MediaStore.Audio.Playlists.NAME;
    final String[]columns={id,name};
    final Cursor playlists= resolver.query(uri,columns,null,null);

        if(playlists==null)
            {
                Log.e(TAG,"Found no playlists.");
                    return;
            }
    return;
}

有谁可以提供帮助?

解决方法

我认为你的意思是NullPointerException,这意味着你的一个任务是null,然后你尝试访问你想要它的对象的成员.最有可能是解析器,但确保您需要报告的行号和/或使用调试器逐步执行此操作.

c# – 如果异步方法是单线程的,它怎么能在后台运行?

c# – 如果异步方法是单线程的,它怎么能在后台运行?

我正在尝试理解async / await并阅读了大量文章,但我仍然对同步/异步性质感到困惑.

我有以下测试控制台应用程序:

static void Main(string[] args)
{
    var test = FooAsync();
    Console.WriteLine("After FooAsync");

    for (int i = 0; i < 100; i++)
        Console.WriteLine("After that");

    Console.ReadKey();
}

private static async Task FooAsync()
{
    Console.WriteLine("Before delay");
    await Task.Delay(1);
    Console.WriteLine("After delay");
}

代码提供了以下行的输出:

Before delay
After FooAsync
After that
After that
After that
After that
After delay
After that
.
.

我知道async / await不会创建一个单独的线程进行处理,并且当FooAsync到达await Task.Delay(1)行时,它将返回Main,因为任务还没有完成,但是,因为我们是只有在单个线程上运行才能解释是什么触发FooAsync方法在Main之前的某个任意点恢复,然后Main可以继续?

更新
我把它拿回来,i3arnon和dariogriffo是正确的.代码确实使用了多个线程(正如我之前看到的那样,在调试器中查看或完成了kha建议的显而易见的事情).我对下一页https://msdn.microsoft.com/en-us/library/hh191443.aspx#BKMK_Threads中的“线程”部分感到困惑,没有意识到“延续”实际上是指一旦“等待”任务完成就立即运行的继续任务计划.

解决方法

这不是单线程的.

当延迟任务完成时,方法的其余部分将发布到ThreadPool并与主线程同时运行.这里的“触发器”是在Task.Delay中使用的内部System.Threading.Timer的回调.

此行为取决于SynchronizationContext.在UI环境中,这将被发布到相同的UI线程,并且必须等到该线程空闲.

如果您一直在等待从FooAsync返回的任务,那么每次只能运行一个线程.

c# 线程池:开启10个线程运行Fibonacci,并在所有线程运行完后,得出结果。

c# 线程池:开启10个线程运行Fibonacci,并在所有线程运行完后,得出结果。

namespace CAThreadPool
{
    class ThreadpoolDemo6
    {
        static void Main(string[] args)
        {
            const int FibonacciCalculations = 10;

            // One event is used for each Fibonacci object.
            ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations];
            Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations];
            Random r = new Random();

            // Configure and start threads using ThreadPool.
            Console.WriteLine("launching {0} tasks...", FibonacciCalculations);
            for (int i = 0; i < FibonacciCalculations; i++)
            {
                doneEvents[i] = new ManualResetEvent(false);
                Fibonacci f = new Fibonacci(r.Next(20, 40), doneEvents[i]);
                fibArray[i] = f;
                ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
            }

            // Wait for all threads in pool to calculate.
            WaitHandle.WaitAll(doneEvents);
            Console.WriteLine("All calculations are complete.");

            // Display the results. 
            for (int i = 0; i < FibonacciCalculations; i++)
            {
                Fibonacci f = fibArray[i];
                Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN);
            }
            Console.ReadKey();
        }
    }
    public class Fibonacci
    {
        private int _n;
        private int _fibOfN;
        private ManualResetEvent _doneEvent;

        public int N { get { return _n; } }
        public int FibOfN { get { return _fibOfN; } }
        // Constructor. 
        public Fibonacci(int n, ManualResetEvent doneEvent)
        {
            _n = n;
            _doneEvent = doneEvent;
        }
        // Recursive method that calculates the Nth Fibonacci number. 
        public int Calculate(int n)
        {
            if (n <= 1)
            {
                return n;
            }
            return Calculate(n - 1) + Calculate(n - 2);
        }
        // Wrapper method for use with thread pool. 
        public void ThreadPoolCallback(Object threadContext)
        {
            int threadIndex = (int)threadContext;
            Console.WriteLine("thread {0} started...", threadIndex);
            _fibOfN = Calculate(_n);
            Console.WriteLine("thread {0} result calculated...", threadIndex);
            _doneEvent.Set();
        }
    }
}

 

ios – complition处理程序关闭是否总是在后台线程运行?

ios – complition处理程序关闭是否总是在后台线程运行?

完成处理程序闭包在ios开发中很常见.例如URLSession类中的dataTask(with:completionHandler :).

UI引擎由主线程管理,URLSession的API调用在后台线程下运行,如果处理程序中需要UI更新,则需要将其调度到主线程.

问题1:
是否所有来自ios框架的完成Handler闭包都在后台线程中运行?

问题1.1:
例如,开发人员创建的所有转义闭包是否都在后台线程中运行?

问题2:
我在iPhone X模拟器中看到了多达8个线程.哪一个是主线程,哪一个是ios中的后台线程?他们有不同的优先级和计算能力吗?

解决方法

请记住,您确实询问的是队列和线程,而不仅仅是完成处理程序和闭包.任何类型的代码都在队列(由一个或多个线程组成)上执行.在这方面,完成处理程序关闭没有什么特别之处.

Q1 – 大多数iOS SDK提供的完成处理程序在后台队列上调用,但除非文档明确说明调用它的队列,否则不做这个假设.甚至可以将URLSession配置为在特定队列(包括主队列)上运行.

Q1.1 – 您编写的闭包在您调用它们的任何队列上运行.没有魔法使它们在后台队列上运行.

Q2 – 第一个线程始终是主队列的唯一线程.所有其他线程都来自后台队列.每个线程可以具有基于其队列的属性给出的任何优先级.

您应该查看Dispatch文档以获取更多详细信息,尤其是dispatchQueue.

今天的关于Python-线程-如何创建播放列表函数以在后台通过线程运行?python 创建线程的分享已经结束,谢谢您的关注,如果想了解更多关于android – 如何创建播放列表、c# – 如果异步方法是单线程的,它怎么能在后台运行?、c# 线程池:开启10个线程运行Fibonacci,并在所有线程运行完后,得出结果。、ios – complition处理程序关闭是否总是在后台线程运行?的相关知识,请在本站进行查询。

对于想了解延迟的onClick响应React App的读者,本文将提供新的信息,我们将详细介绍仅适用于第二次点击,但不适用于第一次点击,并且为您提供关于API 路由适用于邮递员,但不适用于客户端应用程序、AsyncTask适用于Android 2.3.3,但不适用于ICS、Bootstrap 表行单击适用于桌面,但不适用于 iOS、click()确实执行了一次点击,但以错误结束的有价值信息。

本文目录一览:

延迟的onClick响应React App(仅适用于第二次点击,但不适用于第一次点击)

延迟的onClick响应React App(仅适用于第二次点击,但不适用于第一次点击)

在设置返回api数据的状态时,您无需从tenDrinks函数返回值。

只需在渲染器中获取randomDrinks的值,就会随着状态的变化而更新

{ randomDrinks.map((drink) => (
        <div key={drink.idDrink}>{drink.strDrink}</div>
    )) 
}

使您的完整代码看起来像这样

const Home = () => {
    const [randomDrinks,setRandomDrinks] = useState([]);

    const tenDrinks = async () => {
      const config = {
         ...
      } ;

      await axios(config)
        .then((res) => setRandomDrinks(res.data.drinks)) // This updates the value of randomDrinks
        .catch(console.error); 
    };

    const onClick = () => {
      tenDrinks();
    };

    return (
      <div>
        <button onClick={onClick}>Get 10 random cocktails</button>
        {/** This will always rendered the current state value of randomDrinks */}
        { randomDrinks.map((drink) => (
            <div key={drink.idDrink}>{drink.strDrink}</div>
        )) }
      </div>
    );
};

API 路由适用于邮递员,但不适用于客户端应用程序

API 路由适用于邮递员,但不适用于客户端应用程序

如何解决API 路由适用于邮递员,但不适用于客户端应用程序?

我有以下路由,由 /api/mentors/details 调用

router.route(''/details'').put(
  asyncHandler(async (req,res) => {
    let token;
    if (
      req.headers.authorization &&
      req.headers.authorization.startsWith(''Bearer'')
    ) {
      try {
        console.log(''This wants to be claled'');
        token = req.headers.authorization.split('' '')[1];
        const decoded = jwt.verify(token,''abc123'');
        const user = await User.findById(decoded.id).select(''-password'');
        if (user) {
          const mentor = await Mentor.findOne({user_linked_to: user._id});
          if (mentor) {
            mentor.name = req.body.name || mentor.name;
            mentor.email = req.body.email || mentor.email;
            mentor.bio = req.body.bio || mentor.bio;
            mentor.password = req.body.password || mentor.password;
            mentor.university = req.body.university || mentor.university;
            mentor.major = req.body.major || mentor.major;
            mentor.type = req.body.type || mentor.type;
            mentor.housing = req.body.housing || mentor.housing;
            mentor.clubs = req.body.clubs || mentor.clubs;
            mentor.days_available =
              req.body.days_available || mentor.days_available;
            mentor.isAvailable = req.body.isAvailable || mentor.isAvailable;
            mentor.image = req.body.image || mentor.image;
            mentor.isverified = false;
            mentor.price = req.body.price || mentor.price;

            const updatedMentor = await mentor.save();

            if (updatedMentor) {
              res.status(201).json(updatedMentor);
            } else {
              res.status(404);
              throw new Error(''Mentor Could not be updated'');
            }
          } else {
            res.status(404);
            throw new Error(''Mentor not found'');
          }
        } else {
          res.status(404);
          throw new Error(''User not found'');
        }
        // needs changing shouldn''t really be passing id''s through requests
        //instead current User''s Id should be checked and that''s how the authenticated privacy for this route should also be enforced
      } catch (error) {
        console.error(error);
        res.status(401);
        throw new Error(''Not authorized,token Failed'');
      }
    }
  })
);

当我使用邮递员调用这条路线时,它可以工作并且我能够更新相应导师的详细信息。

使用以下操作在我的 React 应用程序中调用相同的路由:

export const updateMentorDetails = (mentor) => async (dispatch,getState) => {
  dispatch({
    type: ''MENTOR_UPDATE_DETAILS_REQUEST'',});
  try {
    const {
      userLogin: {userInfo},} = getState();
    console.log(userInfo);
    const config = {
      headers: {
        ''Content-Type'': ''application/json'',Authorization: `Bearer ${userInfo.token}`,},};
    console.log(mentor);
    const {data} = await axios.put(`/api/mentors/details`,mentor,config);

    dispatch({
      type: ''MENTOR_UPDATE_DETAILS_SUCCESS'',payload: data,});
  } catch (error) {
    dispatch({
      type: ''MENTOR_UPDATE_DETAILS_FAIL'',payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,});
  }
};

使用以下数据调用此操作,如下所示:

dispatch(
      updateMentorDetails({
        id: mentor._id,name: name,email: email,password: password,days_available: days_available,bio: bio,major: major,housing: housing,isAvailable: isAvailable,price: price,university: university,type: type,clubs: clubs,image: image,})

但是,当我尝试使用此方法时,出现错误:未授权,令牌失败。

我使用了类似的方法来更新我的应用程序中的另一种类型的模型,并且该方法有效,但由于某种原因,尽管邮递员中的路线有效,但这种方法无效。有人可以帮我解决这个问题吗。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

AsyncTask适用于Android 2.3.3,但不适用于ICS

AsyncTask适用于Android 2.3.3,但不适用于ICS

我有tabactivity,每个标签都有ActivityGroup.在Forth Tab中,ForthActivityGroup有一个MyAsyncActivity类.在MyAsyncAcitivity中,我有这个代码.
我有这个 Android AsyncTask代码.调用doInBackground(String .. params)并在Android 2.3.3上打印日志,但不在Android 4.0上打印.请SomeBody告诉我我的想法?

public class getXML extends AsyncTask<String,Integer,String>{
        private final ProgressDialog dialog = new ProgressDialog(this);

        @Override
        protected void onPreExecute() {
            this.dialog.setMessage("Loading...");
            this.dialog.show();
        }

        @Override
        protected String doInBackground(String... params) {
            Log.d("Payment","do background");

            return "result";
        }

        @Override
        protected void onPostExecute(String result) {
            if (this.dialog.isShowing()) {
                this.dialog.dismiss();
            }

    }

解决方法

用这个:

AsyncTask task = new YourTask();
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
   task.execute(params);
} else {
   task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,params);
}

Bootstrap 表行单击适用于桌面,但不适用于 iOS

Bootstrap 表行单击适用于桌面,但不适用于 iOS

如何解决Bootstrap 表行单击适用于桌面,但不适用于 iOS?

这是适用于桌面浏览器的代码,但不适用于 iOS。

tankLevelTable.on(''click-row.bs.table'',function (e,row) {
    customer = row.customerName; 
    indexModal.find(''.modal-title'').text(customer + '' - Tank Options'');
    indexModal.modal(''show'');
});

我已经尝试在页面中的各种 HTML 元素上放置一个 onclick = "void(0)",但它仍然不起作用。为事物分配常规点击事件在 iOS 上确实有效,只是不是这个特定的引导表事件。有人有什么建议吗?

此外,这里是 HTML:

 <div onclick="alert(''hi there'');" >
        <table id="tankLevelTable"https://www.jb51.cc/tag/dis/" target="_blank">display table table-bordered table-striped" data-url="https://xxx.xxx.com/customertanklevel" data-row-data-toggle="table">
            <thead>
                <tr>
                    <!--<th data-field="State" data-checkBox="true" data-formatter="test"></th>-->
                    <th data-field="customerName">Customer</th>
                    <th data-field="tankLevelString">gallons</th>
                    <th data-field="fuelType">Fuel</th>
                    <th data-field="fuelHeightString">Height</th>
                </tr>
            </thead>
        </table>
</div>

在桌面站点上,当单击一行时,警报和行单击事件都会触发(先发出警报,然后单击行)。但在 iPhone iOS(和 Android)上,只会触发警报。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

click()确实执行了一次点击,但以错误结束

click()确实执行了一次点击,但以错误结束

将后端从uia切换到win32解决了我的问题:

sw = Application(backend='win32').connect(title=APPLICATION_TITLE)

这也使自动化速度更快(从〜5秒/ op到

关于延迟的onClick响应React App仅适用于第二次点击,但不适用于第一次点击的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于API 路由适用于邮递员,但不适用于客户端应用程序、AsyncTask适用于Android 2.3.3,但不适用于ICS、Bootstrap 表行单击适用于桌面,但不适用于 iOS、click()确实执行了一次点击,但以错误结束的相关知识,请在本站寻找。

本文将带您了解关于具有用于请求身份验证的中间件和JWT的Web API的新内容,同时我们还将为您解释Python,Flask引发DecodeError的相关知识,另外,我们还将为您提供关于.NET Core WebAPI集成JWT,实现身份验证、1、传统身份验证和JWT的身份验证、ASP.NET Web API 的 JWT 身份验证、asp.net – 如何使用JWT对角度SPA的Web Api 2进行用户身份验证?的实用信息。

本文目录一览:

具有用于请求身份验证的中间件和JWT的Web API(Python,Flask)引发DecodeError(“签名验证失败”)

具有用于请求身份验证的中间件和JWT的Web API(Python,Flask)引发DecodeError(“签名验证失败”)

如何解决具有用于请求身份验证的中间件和JWT的Web API(Python,Flask)引发DecodeError(“签名验证失败”)?

我无法解码通过请求标头收到的令牌。

应用程序:

from flask import Flask
from flask import jsonify
from flask_restplus import Resource,Api
from helpers.load import get_env as _
from middleware.environment_middleware import EnvironmentMiddleware
from flask_jwt_extended import JWTManager


app = Flask(__name__)
app.config[''sqlALCHEMY_DATABASE_URI''] = _(''DATABASE_URI'')
app.config[''sqlALCHEMY_DATABASE_URI''] = _(''DATABASE_URI'')
app.config[''SECRET_KEY''] = _(''SECRET_KEY'')
app.config[''JWT_SECRET_KEY''] = _(''JWT_SECRET'')
app.wsgi_app = EnvironmentMiddleware(app.wsgi_app)

jwt = JWTManager(app)
api = Api(app)
jwt._set_error_handler_callbacks(api)

中间件类:

from werkzeug.wrappers import Request,Response,ResponseStream
from helpers.load import load_db_env
from flask_jwt_extended import get_jwt_identity,jwt_required,verify_jwt_in_request
import jwt


class EnvironmentMiddleware():
    def __init__(self,app):
        self.app = app

    def __call__(self,environ,start_response):
        request = Request(environ)
        if request.headers:
            params = load_db_env(request.headers.get(''Whitelabel''))
            jwt.decode(request.headers.get(''Authorization'').replace(''Bearer '',''''),params[''JWT_SECRET''],algorithm=''HS256'')
            return self.app(environ,start_response)

        res = Response(u''Unauthorized.'',mimetype=''application/json'',status=401)
        return res(environ,start_response)

load_db_env 根据“ whitelabel”参数(包括 JWT_SECRET )和我的 environ 带来了我数据库中所有参数的字典。身份验证所需的数据,标题等。

但是出于某些原因,我无法从验证和识别用户的请求中解码并找到Bearer令牌内的信息。

Traceback (most recent call last):
  File "<string>",line 1,in <module>
  File "/home/bela/dev/bela/lib/python3.8/site-packages/jwt/api_jwt.py",line 63,in decode
    decoded = super(PyJWT,self).decode(jwt,key,verify,algorithms,File "/home/bela/dev/bela/lib/python3.8/site-packages/jwt/api_jws.py",line 115,in decode
    self._verify_signature(payload,signing_input,header,signature,line 186,in _verify_signature
    raise DecodeError(''Signature verification Failed'')
jwt.exceptions.DecodeError: Signature verification Failed

我希望我很清楚,我来自巴西,我的英语不是最好的。

Obrigada! :*

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

.NET Core WebAPI集成JWT,实现身份验证

.NET Core WebAPI集成JWT,实现身份验证

前两篇文章给大家介绍了在.NET Core中如何使用Swagger的文章,那今天给大家分享一下JWT

在做接口开发的同学可能都有感受,我的接口如何保护的问题,如果没有身份验证,那不是接口完全暴露在外面,任意使人调用,这显然不是我们想要的一种结果。当然做身份验证的方式有多种,今天给大家讲一种比较流行了,标准的身份验证JWT

什么是JWT?

随着技术的发展,分布式web应用的普及,通过session管理用户登录状态成本越来越高,因此慢慢发展成为token的方式做登录身份校验,然后通过token去取redis中的缓存的用户信息,随着之后jwt的出现,校验方式更加简单便捷化,无需通过redis缓存,而是直接根据token取出保存的用户信息,以及对token可用性校验,单点登录更为简单。

JWT的结构体是什么样的?

JWT由三部分组成,分别是头信息、有效载荷、签名,中间以(.)分隔

(1)header(头信息)

由两部分组成,令牌类型(即:JWT)、散列算法(HMAC、RSASSA、RSASSA-PSS等)

(2)Payload(有效载荷)

JWT的第二部分是payload,其中包含claims。claims是关于实体(常用的是用户信息)和其他数据的声明,claims有三种类型: registered, public, and private claims。

Registered claims: 这些是一组预定义的claims,非强制性的,但是推荐使用, iss(发行人), exp(到期时间), sub(主题), aud(观众)等;

Public claims: 自定义claims,注意不要和JWT注册表中属性冲突

Private claims: 这些是自定义的claims,用于在同意使用这些claims的各方之间共享信息,它们既不是Registered claims,也不是Public claims。

(3)Signature

要创建签名部分,必须采用编码的Header,编码的Payload,秘钥,Header中指定的算法,并对其进行签名。

JWT使用流程:

JWT在.NET Core项目中的具体用法:

(1)在ConfigureServices方法中添加JWT相关代码:

(2)在Configure方法中添加JWT代码:

(3)创建一个JWT服务类:

(4)在接口类或方法上标记身份验证:

到此为止,JWT的基本用法就结束,非常简单和方便,接下来我们用postman测试一下JWT是否生效:

(1)当我们在不登录的情况下,访问接口看看是什么现象:

我们发现接口返回提示:401 Unauthorized

(2)我们先调用登录接口,先计算得到token,然后再来请求试试:

登录成功后,接口返回了token值

(3)将token复制粘贴到下方,请求业务接口,成功调用:

1、传统身份验证和JWT的身份验证

1、传统身份验证和JWT的身份验证

1、传统身份验证和JWT的身份验证

传统身份验证:

      HTTP 是一种没有状态的协议,也就是它并不知道是谁是访问应用。这里我们把用户看成是客户端,客户端使用用户名还有密码通过了身份验证,不过下回这个客户端再发送请求时候,还得再验证一下。 解决的方法就是,当用户请求登录的时候,如果没有问题,我们在服务端生成一条记录,这个记录里可以说明一下登录的用户是谁,然后把这条记录的 ID 号发送给客户端,客户端收到以后把这个 ID 号存储在 Cookie 里,下次这个用户再向服务端发送请求的时候,可以带着这个 Cookie ,这样服务端会验证一个这个 Cookie 里的信息,看看能不能在服务端这里找到对应的记录,如果可以,说明用户已经通过了身份验证,就把用户请求的数据返回给客户端。 上面说的就是 Session,我们需要在服务端存储为登录的用户生成的 Session ,这些 Session 可能会存储在内存,磁盘,或者数据库里。我们可能需要在服务端定期的去清理过期的 Session 。
 
安装:
pip install djangorestframework_jwt

 

JWT的身份验证:

使用基于 Token 的身份验证方法,在服务端不需要存储用户的登录记录。大概的流程是这样的:


1、客户端使用用户名跟密码请求登录
2、服务端收到请求,去验证用户名与密码
3、验证成功后,服务端会签发一个 Token,再把这个 Token 发送给客户端
4、客户端收到 Token 以后可以把它存储起来,比如放在 Cookie 里或者 Local Storage 里
5、客户端每次向服务端请求资源的时候需要带着服务端签发的 Token
6、服务端收到请求,然后去验证客户端请求里面带着的 Token,如果验证成功,就向客户端返回请求的数据

2、JWT的token组成

    实施 Token 验证的方法挺多的,还有一些标准方法,比如 JWT,读作:jot ,表示:JSON Web Tokens 。JWT 标准的 Token 有三个部分:
    header(头部)
    payload(数据)
    signature(签名)
    中间用点分隔开,并且都会使用 Base64 编码,所以真正的 Token 看起来像这样:

eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJuaW5naGFvLm5ldCIsImV4cCI6IjE0Mzg5NTU0NDUiLCJuYW1lIjoid2FuZ2hhbyIsImFkbWluIjp0cnVlfQ.SwyHTEx_RQppr97g4J5lKXtabJecpejuef8AqKYMAJc


头部:

每个 JWT token 里面都有一个 header,也就是头部数据。里面包含了使用的算法,这个 JWT 是不是带签名的或者加密的。主要就是说明一下怎么处理这个 JWT token 。

头部里包含的东西可能会根据 JWT 的类型有所变化,比如一个加密的 JWT 里面要包含使用的加密的算法。唯一在头部里面要包含的是 alg 这个属性,如果是加密的 JWT,这个属性的值就是使用的签名或者解密用的算法。如果是未加密的 JWT,这个属性的值要设置成 none

示例:


 
 

意思是这个 JWT 用的算法是 HS256。上面的内容得用 base64url 的形式编码一下,所以就变成这样:

 
 

Payload:

Payload 里面是 Token 的具体内容,这些内容里面有一些是标准字段,你也可以添加其它需要的内容。下面是标准字段:

  1. iss:Issuer,发行者
  2. sub:Subject,主题
  3. aud:Audience,观众
  4. exp:Expiration time,过期时间
  5. nbf:Not before
  6. iat:Issued at,发行时间
  7. jti:JWT ID

比如下面这个 Payload ,用到了 iss 发行人,还有 exp 过期时间这两个标准字段。另外还有两个自定义的字段,一个是 name ,还有一个是 admin 。

 
 

使用 base64url 编码以后就变成了这个样子:

 
 

Signature:

JWT 的最后一部分是 Signature ,这部分内容有三个部分,先是用 Base64 编码的 header.payload ,再用加密算法加密一下,加密的时候要放进去一个 Secret ,这个相当于是一个密码,这个密码秘密地存储在服务端。

  1. header
  2. payload
  3. secret
 

处理完成以后看起来像这样:

 

最后这个在服务端生成并且要发送给客户端的 Token 看起来像这样:
 
 

客户端收到这个 Token 以后把它存储下来,下回向服务端发送请求的时候就带着这个 Token 。服务端收到这个 Token ,然后进行验证,通过以后就会返回给客户端想要的资源。

 

ASP.NET Web API 的 JWT 身份验证

ASP.NET Web API 的 JWT 身份验证

我正在尝试在我的 Web API 应用程序中支持 JWT 不记名令牌(JSON Web 令牌),但我迷路了。

我看到了对 .NET Core 和 OWIN 应用程序的支持。
我目前在 IIS 中托管我的应用程序。

如何在我的应用程序中实现此身份验证模块?有什么方法可以使用<authentication>类似于我使用表单/Windows 身份验证的方式的配置?

答案1

小编典典

现在,安全方面发生了很多变化,尤其是 JWT 越来越流行。在这个答案中,我将尝试以最简单和基本的方式解释如何使用 JWT,这样我们就不会迷失在
OWIN、Oauth2、ASP.NET Identity 等的丛林中。

如果您不了解 JWT 令牌,则需要查看:

https://www.rfc-editor.org/rfc/rfc7519

基本上,JWT 令牌如下所示:

<base64-encoded header>.<base64-encoded claims>.<base64-encoded signature>

例子:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImN1b25nIiwibmJmIjoxNDc3NTY1NzI0LCJleHAiOjE0Nzc1NjY5MjQsImlhdCI6MTQ3NzU2NTcyNH0.6MzD1VwA5AcOcajkFyKhLYybr3h13iZjDyHm9zysDFQ

JWT 令牌包含三个部分:

  1. 标头:以 Base64 编码的 JSON 格式
  2. 声明:以 Base64 编码的 JSON 格式。
  3. 签名:基于以 Base64 编码的 Header 和 Claims 创建和签名。

如果您将网站jwt.io与上面的令牌一起使用,您可以对令牌进行解码并看到如下所示:

jwt.io 的屏幕截图,其中包含原始 jwt 源和它所代表的解码JSON

从技术上讲,JWT
使用从标头和声明中签名的签名,并使用标头中指定的安全算法(例如:HMACSHA256)。因此,如果您在其声明中存储任何敏感信息,则必须通过 HTTP 传输
JWT。

现在,为了使用 JWT 身份验证,如果您有旧版 Web Api 系统,则实际上不需要 OWIN 中间件。简单的概念是如何提供 JWT
令牌以及如何在请求到来时验证令牌。就是这样。

在我创建的演示 (github)中,为了保持 JWT
令牌的轻量级,我只存储usernameexpiration time.
但是这样,你必须重新构建新的本地身份(主体)来添加更多信息,比如角色,如果你想做角色授权等。但是,如果你想在 JWT
中添加更多信息,这取决于你:它非常灵活。

您可以使用控制器操作简单地提供 JWT 令牌端点,而不是使用 OWIN 中间件:

public class TokenController : ApiController{    // This is naive endpoint for demo, it should use Basic authentication    // to provide token or POST request    [AllowAnonymous]    public string Get(string username, string password)    {        if (CheckUser(username, password))        {            return JwtManager.GenerateToken(username);        }        throw new HttpResponseException(HttpStatusCode.Unauthorized);    }    public bool CheckUser(string username, string password)    {        // should check in the database        return true;    }}

这是一个幼稚的行为;在生产中,您应该使用 POST 请求或基本身份验证端点来提供 JWT 令牌。

如何基于 生成令牌username

您可以使用System.IdentityModel.Tokens.Jwt从 Microsoft 调用的 NuGet
包来生成令牌,如果您愿意,甚至可以使用其他包。在演示中,我使用HMACSHA256with SymmetricKey

/// <summary>/// Use the below code to generate symmetric Secret Key///     var hmac = new HMACSHA256();///     var key = Convert.ToBase64String(hmac.Key);/// </summary>private const string Secret = "db3OIsj+BXE9NZDy0t8W3TcNekrF+2d/1sFnWG4HnV8TZY30iTOdtVWJG8abWvB1GlOgJuQZdcF2Luqm/hccMw==";public static string GenerateToken(string username, int expireMinutes = 20){    var symmetricKey = Convert.FromBase64String(Secret);    var tokenHandler = new JwtSecurityTokenHandler();    var now = DateTime.UtcNow;    var tokenDescriptor = new SecurityTokenDescriptor    {        Subject = new ClaimsIdentity(new[]        {            new Claim(ClaimTypes.Name, username)        }),        Expires = now.AddMinutes(Convert.ToInt32(expireMinutes)),        SigningCredentials = new SigningCredentials(            new SymmetricSecurityKey(symmetricKey),             SecurityAlgorithms.HmacSha256Signature)    };    var stoken = tokenHandler.CreateToken(tokenDescriptor);    var token = tokenHandler.WriteToken(stoken);    return token;}

提供 JWT 令牌的端点已完成。

请求到来时如何验证 JWT?

在演示中,我构建
JwtAuthenticationAttribute了继承自IAuthenticationFilter(有关身份验证过滤器的更多详细信息,请参见此处)。

使用此属性,您可以验证任何操作:您只需将此属性放在该操作上。

public class ValueController : ApiController{    [JwtAuthentication]    public string Get()    {        return "value";    }}

如果要验证 WebAPI 的所有传入请求(不特定于控制器或操作),也可以使用 OWIN 中间件或 DelegateHander

以下是身份验证过滤器的核心方法:

private static bool ValidateToken(string token, out string username){    username = null;    var simplePrinciple = JwtManager.GetPrincipal(token);    var identity = simplePrinciple.Identity as ClaimsIdentity;    if (identity == null || !identity.IsAuthenticated)        return false;    var usernameClaim = identity.FindFirst(ClaimTypes.Name);    username = usernameClaim?.Value;    if (string.IsNullOrEmpty(username))       return false;    // More validate to check whether username exists in system    return true;}protected Task<IPrincipal> AuthenticateJwtToken(string token){    string username;    if (ValidateToken(token, out username))    {        // based on username to get more information from database         // in order to build local identity        var claims = new List<Claim>        {            new Claim(ClaimTypes.Name, username)            // Add more claims if needed: Roles, ...        };        var identity = new ClaimsIdentity(claims, "Jwt");        IPrincipal user = new ClaimsPrincipal(identity);        return Task.FromResult(user);    }    return Task.FromResult<IPrincipal>(null);}

工作流程是使用 JWT 库(上面的 NuGet 包)来验证 JWT
令牌,然后返回ClaimsPrincipal。您可以执行更多验证,例如检查系统上是否存在用户,并根据需要添加其他自定义验证。

验证 JWT 令牌并取回本金的代码:

public static ClaimsPrincipal GetPrincipal(string token){    try    {        var tokenHandler = new JwtSecurityTokenHandler();        var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken;        if (jwtToken == null)            return null;        var symmetricKey = Convert.FromBase64String(Secret);        var validationParameters = new TokenValidationParameters()        {            RequireExpirationTime = true,            ValidateIssuer = false,            ValidateAudience = false,            IssuerSigningKey = new SymmetricSecurityKey(symmetricKey)        };        SecurityToken securityToken;        var principal = tokenHandler.ValidateToken(token, validationParameters, out securityToken);        return principal;    }    catch (Exception)    {        //should write log        return null;    }}

如果验证了 JWT 令牌并返回了委托人,您应该构建一个新的本地身份并将更多信息放入其中以检查角色授权。

请记住在全局范围内添加config.Filters.Add(newAuthorizeAttribute());(默认授权),以防止对您的资源的任何匿名请求。

您可以使用 Postman 来测试演示:

请求令牌(我上面提到的幼稚,仅用于演示):

GET http://localhost:{port}/api/token?username=cuong&password=1

将 JWT 令牌放入授权请求的标头中,例如:

GET http://localhost:{port}/api/valueAuthorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImN1b25nIiwibmJmIjoxNDc3NTY1MjU4LCJleHAiOjE0Nzc1NjY0NTgsImlhdCI6MTQ3NzU2NTI1OH0.dSwwufd4-gztkLpttZsZ1255oEzpWCJkayR_4yvNL1s

该演示可以在这里找到:https
://github.com/cuongle/WebApi.Jwt

asp.net – 如何使用JWT对角度SPA的Web Api 2进行用户身份验证?

asp.net – 如何使用JWT对角度SPA的Web Api 2进行用户身份验证?

我正在尝试将AngularJS单页面应用程序(SPA)中的身份验证设置为基于OWIN构建的Web Api.这是我的……

这是登录功能(API中的AuthenticationController上的POST操作)

public HttpResponseMessage login(Credentials creds)
    {
        if (creds.Password == "password" && creds.Username.ToLower() == "username")
        {
            var user = new User { UserId = 101,Name = "John Doe",Role = "admin" };

            var tokenDescriptor = new SecurityTokenDescriptor()
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name,user.Name),new Claim(ClaimTypes.Role,user.Role)
                }),AppliesToAddress = "http://localhost:/8080",TokenIssuerName = "myApi",SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(TestApp.Api.Startup.GetBytes("ThisIsTopSecret")),"http://www.w3.org/2001/04/xmldsig-more#hmac-sha256","http://www.w3.org/2001/04/xmlenc#sha256")
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var token = tokenHandler.Createtoken(tokenDescriptor);
            var tokenString = tokenHandler.Writetoken(token);

            return Request.CreateResponse<LoginResponse>(HttpStatusCode.Accepted,new LoginResponse { User = user,AuthToken = tokenString });
        }

        return Request.CreateResponse(HttpStatusCode.Unauthorized);
    }

这是我的OWIN启动配置

public void Configuration(IAppBuilder app)
    {
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        HttpConfiguration config = new HttpConfiguration();
        config.Routes.MapHttpRoute(
            name: "Default",routeTemplate: "{controller}"
        );

        var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
        jsonSettings.Formatting = Formatting.Indented;
        jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        app.UseWebApi(config);

        app.UseJwtBearerAuthentication(
        new JwtBearerAuthenticationoptions
        {
            AuthenticationMode = AuthenticationMode.Active,AllowedAudiences = new[] { "http://localhost:8080" },IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
            {
                new SymmetricKeyIssuerSecurityTokenProvider("myApp",TestApp.Api.Startup.GetBytes("ThisIsTopSecret"))
            }
        });
    }

这是我用来调用具有Authorized属性的API中的控制器的角度代码.

$http({ method: 'GET',url: 'http://localhost:5000/Admin',headers: { 'Content-Type': 'application/json','Authorization': 'Bearer ' + Session.token }})
          .then(function (res) {
              return res.data;
          });

当我登录时,我将返回的令牌作为字符串.然后我将它存储在我的客户端Session中.然后我把它拿到我的标题中以备后续请求.

当我尝试在API中调用“授权”操作时,即使我的令牌通过请求的标头传入,我也会获得401响应.

我是JWT的新手,所以我可能完全偏离我的方法.任何建议都会很棒.

解决方法

我相信这是一个操作秩序的事情.将app.UseJwt语句移动到app.UseWebApi行上方.

app.UseJwtBearerAuthentication(
    new JwtBearerAuthenticationoptions
    {
        AuthenticationMode = AuthenticationMode.Active,IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
        {
            new SymmetricKeyIssuerSecurityTokenProvider("myApp",TestApp.Api.Startup.GetBytes("ThisIsTopSecret"))
        }
    });

 app.UseWebApi(config);

关于具有用于请求身份验证的中间件和JWT的Web APIPython,Flask引发DecodeError的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于.NET Core WebAPI集成JWT,实现身份验证、1、传统身份验证和JWT的身份验证、ASP.NET Web API 的 JWT 身份验证、asp.net – 如何使用JWT对角度SPA的Web Api 2进行用户身份验证?等相关知识的信息别忘了在本站进行查找喔。

本文将介绍Docker Golang客户端ContainerAttach在阅读器中返回标准输入的详细情况,特别是关于golang docker api的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于A human-machine collaboration to defend against cyberattacks、Basic concepts of docker/kubernete/kata-container、centos rancher 通过本机 docker images 新增 container、Configuring and Running Django + Celery in Docker Containers的知识。

本文目录一览:

Docker Golang客户端ContainerAttach在阅读器中返回标准输入(golang docker api)

Docker Golang客户端ContainerAttach在阅读器中返回标准输入(golang docker api)

如何解决Docker Golang客户端ContainerAttach在阅读器中返回标准输入?

我是Go的新手,它试图使用Docker客户端来附加并获取对我发送的命令的响应。

在Docker客户端上使用ContainerAttach方法,我可以连接并获取HijackedResponse,该值使我可以读写容器

我能够使用HijackedResponse.Conn.Write方法传递命令,但是当我使用HijackedResponse.Reader读取结果时,它将读取stdin(我刚刚输入的命令)以及stdout和stderr。

我的问题是,为什么这要返回标准输入?如何设置它,使其仅返回Stdout和Stderr?

这是我的代码

package docker

//This package is responsible for ineracting with the docker containers

import (
    "bufio"
    "context"
    "fmt"
    "os"

    "github.com/docker/docker/api/types"
    "github.com/docker/docker/api/types/container"
    "github.com/docker/docker/client"
)

var ctx context.Context
var cli *client.Client

type Container struct {
    Con     container.ContainerCreateCreatedBody // The container
    Running bool
    In      chan string // Commands going to the Docker container
    Out     chan string // Commands leaving the Docker container
}

func init() {
    InitDocker()
}

func InitDocker() {
    var err error
    ctx = context.Background()
    cli,err = client.NewClientWithOpts(client.FromEnv,client.WithAPIVersionNegotiation())
    if err != nil {
        panic(err)
    }
}

func NewContainer() *Container {
    // Creates a new container
    resp,err := cli.ContainerCreate(ctx,&container.Config{
        Image:        "bash",Entrypoint:   []string{"/bin/bash"},Tty:          true,AttachStdin:  true,AttachStdout: true,AttachStderr: true,OpenStdin:    true,},nil,"")
    if err != nil {
        panic(err)
    }

    con := &Container{Con: resp,Running: false,In: make(chan string),Out: make(chan string)}
    // fmt.Println("New container: ",resp.ID)
    return con
}

func InitAndruncontainer() *Container {
    // fmt.Println("Creating new container")

    // Transfer pid1 process to container and start it
    con := NewContainer()
    // copy over Pid1 to the container (Service that runs the code on the container)

    // Start container
    con.Start()

    // Attach Stdin & stdout to pid1
    con.Attach()

    return con
}

func (c *Container) Start() {
    if err := cli.ContainerStart(ctx,c.Con.ID,types.ContainerStartOptions{}); err != nil {
        panic(err)
    }
    c.Running = true
}

func (c *Container) Attach() {
    // Todo
    attachOpts := types.ContainerAttachOptions{
        Stream: true,Stdout: true,Stderr: true,Stdin:  true,//  DetachKeys string
        //  Logs       bool
    }

    // Attach to container
    hijack,err := cli.ContainerAttach(ctx,attachOpts)
    if err != nil {
        fmt.Println("Error Attaching")
        panic(err)
    }

    // Watch stdin & stdout
    go c.WatchContainerIn(&hijack)
    go c.WatchContainerOut(&hijack)

}

func (c *Container) WatchContainerIn(hijackRes *types.HijackedResponse) {
    // Watch in
    for {

        cmd := <-c.In
        fmt.Println("IN",cmd)

        hijackRes.Conn.Write([]byte(cmd + "\n"))
    }

}
func (c *Container) WatchContainerOut(hijackRes *types.HijackedResponse) {

    scanner := bufio.NewScanner(hijackRes.Reader)

    for scanner.Scan() {

        in := scanner.Text()

        c.Out <- in

    }

    // }
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr,"reading standard input:",err)
    }

    c.Running = false

}

func (c *Container) StopContainer() {
    // Stops a continer
    if err := cli.ContainerStop(ctx,nil); err != nil {
        panic(err)
    }
    c.Running = false
}

func DeleteContainer() {
    // Todo
    // Stops and deletes a container
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

A human-machine collaboration to defend against cyberattacks

A human-machine collaboration to defend against cyberattacks

http://news.mit.edu/2020/patternex-machine-learning-cybersecurity-0221


Being a cybersecurity analyst at a large company today is a bit like looking for a needle in a haystack — if that haystack were hurtling toward you at fiber optic speed.

Every day, employees and customers generate loads of data that establish a normal set of behaviors. An attacker will also generate data while using any number of techniques to infiltrate the system; the goal is to find that “needle” and stop it before it does any damage.

The data-heavy nature of that task lends itself well to the number-crunching prowess of machine learning, and an influx of AI-powered systems have indeed flooded the cybersecurity market over the years. But such systems can come with their own problems, namely a never-ending stream of false positives that can make them more of a time suck than a time saver for security analysts.

MIT startup PatternEx starts with the assumption that algorithms can’t protect a system on their own. The company has developed a closed loop approach whereby machine-learning models flag possible attacks and human experts provide feedback. The feedback is then incorporated into the models, improving their ability to flag only the activity analysts care about in the future.

“Most machine learning systems in cybersecurity have been doing anomaly detection,” says Kalyan Veeramachaneni, a co-founder of PatternEx and a principal research scientist at MIT. “The problem with that, first, is you need a baseline [of normal activity]. Also, the model is usually unsupervised, so it ends up showing a lot of alerts, and people end up shutting it down. The big difference is that PatternEx allows the analyst to inform the system and then it uses that feedback to filter out false positives.”

The result is an increase in analyst productivity. When compared to a generic anomaly detection software program, PatternEx’s Virtual Analyst Platform successfully identified 10 times more threats through the same number of daily alerts, and its advantage persisted even when the generic system gave analysts five times more alerts per day.

First deployed in 2016, today the company’s system is being used by security analysts at large companies in a variety of industries along with firms that offer cybersecurity as a service.

Merging human and machine approaches to cybersecurity

Veeramachaneni came to MIT in 2009 as a postdoc and now directs a research group in the Laboratory for Information and Decision Systems. His work at MIT primarily deals with big data science and machine learning, but he didn’t think deeply about applying those tools to cybersecurity until a brainstorming session with PatternEx co-founders Costas Bassias, Uday Veeramachaneni, and Vamsi Korrapati in 2013.

Ignacio Arnaldo, who worked with Veeramachaneni as a postdoc at MIT between 2013 and 2015, joined the company shortly after. Veeramachaneni and Arnaldo knew from their time building tools for machine-learning researchers at MIT that a successful solution would need to seamlessly integrate machine learning with human expertise.

“A lot of the problems people have with machine learning arise because the machine has to work side by side with the analyst,” Veeramachaneni says, noting that detected attacks still must be presented to humans in an understandable way for further investigation. “It can’t do everything by itself. Most systems, even for something as simple as giving out a loan, is augmentation, not machine learning just taking decisions away from humans.”

The company’s first partnership was with a large online retailer, which allowed the founders to train their models to identify potentially malicious behavior using real-world data. One by one, they trained their algorithms to flag different types of attacks using sources like Wi-Fi access logs, authentication logs, and other user behavior in the network.

The early models worked best in retail, but Veeramachaneni knew how much businesses in other industries were struggling to apply machine learning in their operations from his many conversations with company executives at MIT (a subject PatternEx recently published a paper on).

“MIT has done an incredible job since I got here 10 years ago bringing industry through the doors,” Veeramachaneni says. He estimates that in the past six years as a member of MIT’s Industrial Liaison Program he’s had 200 meetings with members of the private sector to talk about the problems they’re facing. He has also used those conversations to make sure his lab’s research is addressing relevant problems.

In addition to enterprise customers, the company began offering its platform to security service providers and teams that specialize in hunting for undetected cyberattacks in networks.

Today analysts can build machine learning models through PatternEx’s platform without writing a line of code, lowering the bar for people to use machine learning as part of a larger trend in the industry toward what Veeramachaneni calls the democratization of AI.

“There’s not enough time in cybersecurity; it can’t take hours or even days to understand why an attack is happening,” Veeramachaneni says. “That’s why getting the analyst the ability to build and tweak machine learning models  is the most critical aspect of our system.”

Giving security analysts an army

PatternEx’s Virtual Analyst Platform is designed to make security analysts feel like they have an army of assistants combing through data logs and presenting them with the most suspicious behavior on their network.

The platform uses machine learning models to go through more than 50 streams of data and identify suspicious behavior. It then presents that information to the analyst for feedback, along with charts and other data visualizations that help the analyst decide how to proceed. After the analyst determines whether or not the behavior is an attack, that feedback is incorporated back into the models, which are updated across PatternEx’s entire customer base.

“Before machine learning, someone would catch an attack, probably a little late, they might name it, and then they’ll announce it, and all the other companies will call and find out about it and go in and check their data,” Veeramachaneni says. “For us, if there’s an attack, we take that data, and because we have multiple customers, we have to transfer that in real time to other customer’s data to see if it’s happening with them too. We do that very efficiently on a daily basis.”

The moment the system is up and running with new customers, it is able to identify 40 different types of cyberattacks using 170 different prepackaged machine learning models. Arnaldo notes that as the company works to grow those figures, customers are also adding to PatternEx’s model base by building solutions on the platform that address specific threats they’re facing.

Even if customers aren’t building their own models on the platform, they can deploy PatternEx’s system out of the box, without any machine learning expertise, and watch it get smarter automatically.

By providing that flexibility, PatternEx is bringing the latest tools in artificial intelligence to the people who understand their industries most intimately. It all goes back to the company’s founding principle of empowering humans with artificial intelligence instead of replacing them.

“The target users of the system are not skilled data scientists or machine learning experts — profiles that are hard for cybersecurity teams to hire — but rather domain experts already on their payroll that have the deepest understanding of their data and uses cases,” Arnaldo says.


Basic concepts of docker/kubernete/kata-container

Basic concepts of docker/kubernete/kata-container

Kubereters

An open-source system for automating deployment, scaling, and management of containerized applications;

 

 

 

 

Traditional >> Hypervisor >> Container

Traditional:

  No way to define resource boundaries for applications in a physical server before, run each applications on a different physical server;

Hypervisor: 

  Will run multi VMs on a single physical server''s CPU; 

  Allow applications to be isolated between VMs and provides a level of securiy as the infomation of one application cannot be freely accessed by another     application;

  Each VM is a full machine running all the components, including its own operating system;

Container:

  Have relaxed isolation properties to share the operating system among the applications;

  Lightweight;

  A container has its own filesytem/CPU/memory/process space/..

  Are portable across clouds and OS distributions because they are decoupled from the underlying infrastrucure;

  Benifits of containers:

    1. Agile application creation and deployment: increased ease and efficiency of container image creation compared to VM image use

    2. Continuous development, integrations and deployment:

      provide for reliable and frequent container image build and deployment with quick and easy rollbacks;

    3. Dev and Ops separation of concerns: create application container images at build/release time rather than deployment time, thereby decoupling applications from infrastructure;

    4. Obervability not only surfaces OS-level information and metrics, but also application health and other signals;

    5. Environmental consistency across development, testing, and production; Runs the same on a laptop as it does in the cloud;

    6. Cloud and OS distribution portabilty: Runs on Ubuntu, RHEL, CoreOS, on-prem, Google Kubernetes Engine, and anywhrere else;

    7. Application-centric management;

    8. Loosely coupled, distributed;

    9. Resource isolation;

    10. Resource utilization;

 

Benefits of Kubernetes:

  1.  Service discovery and load balancing    

      kubernetes expose a container using the DNS name or using their own IP address;

      if traffic to a container is high, kubernetes is able to load balance and distribute the network traffic so that the deployment is stable;

  2.  Stroage orchestartion

      automatically mount a storage system of local storages/public cloud providers/..

  3.  Automated rollouts and rollbacks

      automake kubernets to create new containers

  4.  Self-healing

      restart fail containers, kill no-respond containers;

  5.  Automatic bin packing

      tell kubernetes how much CPU and RAM each container needs, kubernets can fit containers onto your nodes to make the best use of you resources;

 

Kubernetes Master

When deploying kubernetes, we wil get a cluster, which is a set of machines (nodes),

that run containerzed applications managed by kubernetes.

A cluster has at least one worker node and at least one master node;

 

Kubernetes Master is a collection of three processes that run on a single node in your cluster, which is designed as the master node;

Three processes:

  Kube-apiserver;

  Kube-controller-manager;

  Kube-scheduler;

 

Individual non-master node in cluster run two processes:

  kubelet

    which communicates with the Kubernetes Master;

    The primary node agent that runs on each node; It can register the node with tha apiserver using one of

      the host name;

      a flag to override the hostname;

      specific logic for a cloud provider;

    

  kube-proxy

    a network proxy which reflects Kubernetes networking services on each node;

    Kubernets network proxy runs on each node, this relects services as defined in the Kubernetes API on each node

    and can do simple TCP/UDP and SCTP stream forwarding or round robin TCP/UDP/SCTP forwarding across a set of backends/

    Service cluster IPs and ports are currently found through Docker-links-compatible   

 

Kubernetes Objects

Kubernetes contains serveral abstractions representing the state of system;

Basic Kubernetes objects include:

  • Pod
  • Service
  • Volume
  • Namespace

 

Kata-container

An open-source project and community working to build a standard implement of lightweight VM that feel and perform like containers, but provide the workload isolation and security advantages of VMs;

 

Kata container Components

  • Agent      -- The Kata-agent runs inside the virtual machine and sets up the container environment
  • KSM throttler   -- An optional utility that monitors containers and deduplicates memory to max container density on a host
  • Proxy      -- A process running on the host and co-ordinates access to the agent running inside the VM
  • Runtime     -- Be invoked by a container manager and provides high-level verbs to manage containersd  
  • Shim        -- A process that runs on the host, acts as though it is the workload ( which actually runs inside the VM), required to be compliant with th expecations of the OCI runtime sepc
  • Hypervisor    -- 
  • Kernel      -- HV uses a linux kernel to boot the guest image

 

 

Docker

Following storage drivers:

  • overlay2     is the preferred storage driver, for all currently supported linux distributions, and requires no extra conf
  • aufs       is the preferred stroage driver for Docker 18.06 or older, when running on Ubuntu 14 on Kernel 3.13 which has no support or ovrlay2
  • devicemapper   is supported, but requires direct-lvm for production environments, because loopback-lvm, while zero-conf, has very poor performance.

centos rancher 通过本机 docker images 新增 container

centos rancher 通过本机 docker images 新增 container

示例目标: 将 centos 本地的 docker image ,通过 rancher 进行 add container

相关步骤:

step 1 : rancher 所在 centos 主机,有相应的 docker images ,如 testapi:v1

step 2 :浏览器访问 rancher ui  -> infrastructure -> Containers -> Add Container

step 3 : 输入 Name , Select Images = testapi:v1 ,进行 create 保存

step 4 : 会出现类似如下错误提示 

               Error (Image [index.docker.io/testapi:v1] failed to pull: repository docker.io/testapi not found: does not exist or no pull access)

step 5 : 回到 centos 主机,通过 docker tag 进行类似如下处理 (模拟已将 docker.io/testapi 下载到本机的效果)

               #docker tag testapi:v1 docker.io/testapi:v1

               进行本地镜像查看

              #docker images

step 6 : 回到 rancher ui, 删掉刚才添加失败的 testapi 容器,

              重新进行如 step 3 的添加, 

               这次就不会再出现 step 4 的 error。 

rancher 直接从本地镜像创建容器完成。

供参考

               

Configuring and Running Django + Celery in Docker Containers

Configuring and Running Django + Celery in Docker Containers

 

Configuring and Running Django + Celery in Docker Containers

 Justyna Ilczuk  Oct 25, 2016  0 Comments

Configuring and Running Django + Celery in Docker Containers

After reading this blog post, you will be able to configure Celery with Django, PostgreSQL, Redis, and RabbitMQ, and then run everything in Docker containers.

Today, you''ll learn how to set up a distributed task processing system for quick prototyping. You will configure Celery with Django, PostgreSQL, Redis, and RabbitMQ, and then run everything in Docker containers. You''ll need some working knowledge of Docker for this tutorial, which you can get in one my previous posts here.

Django is a well-known Python web framework, and Celery is a distributed task queue. You''ll use PostgreSQL as a regular database to store jobs, RabbitMQ as message broker, and Redis as a task storage backend.

Motivation

When you build a web application, sooner or later you''ll have to implement some kind of offline task processing.

Example:

Alice wants to convert her cat photos from .jpg to .png or create a .pdf from her collection of .jpg cat files. Doing either of these tasks in one HTTP request will take too long to execute and will unnecessarily burden the web server - meaning we can''t serve other requests at the same time. The common solution is to execute the task in the background - often on another machine - and poll for the result.  

A simple setup for an offline task processing could look like this:

1. Alice uploads a picture.  
2. Web server schedules job on worker.  
3. Worker gets job and converts photo.  
4. Worker creates some result of the task (in this case, a converted photo).  
5. Web browser polls for the result.  
6. Web browser gets the result from the server.  

This setup looks clear, but it has a serious flaw - it doesn''t scale well. What if Alice has a lot of cat pictures and one server wouldn''t be enough to process them all at once? Or, if there was some other very big job and all other jobs would be blocked by it? Does she care if all of the images are processed at once? What if processing fails at some point?

Frankly, there is a solution that won''t kill your machine every time you get a bigger selection of images. You need something between the web server and worker: a broker. The web server would schedule new tasks by communicating with the broker, and the broker would communicate with workers to actually execute these tasks. You probably also want to buffer your tasks, retry if they fail, and monitor how many of them were processed.

You would have to create queues for tasks with different priorities, or for those suitable for different kinds of workers.

All of this can be greatly simplified by using Celery - an open-source, distributed tasks queue. It works like a charm after you configure it - as long as you do so correctly.

How Celery is built

Celery consists of:

  • Tasks, as defined in your app
  • A broker that routes tasks to workers and queues
  • Workers doing the actual work
  • A storage backend

You can watch a more in-depth introduction to Celery here or jump straight to Celery''s getting started guide.

Your setup

Start with the standard Django project structure. It can be created with django-admin, by running in shell:

$ django-admin startproject myproject

Which creates a project structure:

.
└── myproject
    ├── manage.py
    └── myproject
        ├── __init__.py
        ├── settings.py
        ├── urls.py
        └── wsgi.py

At the end of this tutorial, it''ll look like this:

.
├── Dockerfile
├── docker-compose.yml
├── myproject
│   ├── manage.py
│   └── myproject
│       ├── celeryconf.py
│       ├── __init__.py
│       ├── models.py
│       ├── serializers.py
│       ├── settings.py
│       ├── tasks.py
│       ├── urls.py
│       ├── views.py
│       └── wsgi.py
├── requirements.txt
├── run_celery.sh
└── run_web.sh

Creating containers

Since we are working with Docker 1.12, we need a proper Dockerfile to specify how our image will be built.

Custom container

Dockerfile

# use base python image with python 2.7
FROM python:2.7

# add requirements.txt to the image
ADD requirements.txt /app/requirements.txt

# set working directory to /app/
WORKDIR /app/

# install python dependencies
RUN pip install -r requirements.txt

# create unprivileged user
RUN adduser --disabled-password --gecos '''' myuser  

Our dependencies are:

requirements.txt

Django==1.9.8  
celery==3.1.20  
djangorestframework==3.3.1  
psycopg2==2.5.3  
redis==2.10.5  

I''ve frozen versions of dependencies to make sure that you will have a working setup. If you wish, you can update any of them, but it''s not guaranteed to work.

Choosing images for services

Now we only need to set up RabbitMQ, PostgreSQL, and Redis. Since Docker introduced its official library, I use its official images whenever possible. However, even these can be broken sometimes. When that happens, you''ll have to use something else.

Here are images I tested and selected for this project:

  • Official PostgreSQL image
  • Official Redis image
  • Official RabbitMQ image

Using docker-compose to set up a multicontainer app

Now you''ll use docker-compose to combine your own containers with the ones we chose in the last section.

docker-compose.yml

version: ''2''

services:  
  # PostgreSQL database
  db:
    image: postgres:9.4
    hostname: db
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=postgres
    ports:
      - "5432:5432"

  # Redis
  redis:
    image: redis:2.8.19
    hostname: redis

  # RabbitMQ
  rabbit:
    hostname: rabbit
    image: rabbitmq:3.6.0
    environment:
      - RABBITMQ_DEFAULT_USER=admin
      - RABBITMQ_DEFAULT_PASS=mypass
    ports:
      - "5672:5672"  # we forward this port because it''s useful for debugging
      - "15672:15672"  # here, we can access rabbitmq management plugin

  # Django web server
  web:
    build:
      context: .
      dockerfile: Dockerfile
    hostname: web
    command: ./run_web.sh
    volumes:
      - .:/app  # mount current directory inside container
    ports:
      - "8000:8000"
    # set up links so that web knows about db, rabbit and redis
    links:
      - db
      - rabbit
      - redis
    depends_on:
      - db

  # Celery worker
  worker:
    build:
      context: .
      dockerfile: Dockerfile
    command: ./run_celery.sh
    volumes:
      - .:/app
    links:
      - db
      - rabbit
      - redis
    depends_on:
      - rabbit

Configuring the web server and worker

You''ve probably noticed that both the worker and web server run some starting scripts. Here they are (make sure they''re executable):

run_web.sh

#!/bin/sh

# wait for PSQL server to start
sleep 10

cd myproject  
# prepare init migration
su -m myuser -c "python manage.py makemigrations myproject"  
# migrate db, so we have the latest db schema
su -m myuser -c "python manage.py migrate"  
# start development server on public ip interface, on port 8000
su -m myuser -c "python manage.py runserver 0.0.0.0:8000"  

run_celery.sh

#!/bin/sh

# wait for RabbitMQ server to start
sleep 10

cd myproject  
# run Celery worker for our project myproject with Celery configuration stored in Celeryconf
su -m myuser -c "celery worker -A myproject.celeryconf -Q default -n default@%h"  

The first script - run_web.sh - will migrate the database and start the Django development server on port 8000. 
The second one , run_celery.sh, will start a Celery worker listening on a queue default.

At this stage, these scripts won''t work as we''d like them to because we haven''t yet configured them. Our app still doesn''t know that we want to use PostgreSQL as the database, or where to find it (in a container somewhere). We also have to configure Redis and RabbitMQ.

But before we get to that, there are some useful Celery settings that will make your system perform better. Below are the complete settings of this Django app.

myproject/settings.py

import os

from kombu import Exchange, Queue


BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''megg_yej86ln@xao^+)it4e&amp;ueu#!4tl9p1h%2sjr7ey0)m25f''

# SECURITY WARNING: don''t run with debug turned on in production!
DEBUG = True  
TEMPLATE_DEBUG = True  
ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (  
    ''rest_framework'',
    ''myproject'',
    ''django.contrib.sites'',
    ''django.contrib.staticfiles'',

    # required by Django 1.9
    ''django.contrib.auth'',
    ''django.contrib.contenttypes'',

)

MIDDLEWARE_CLASSES = (  
)

REST_FRAMEWORK = {  
    ''DEFAULT_PERMISSION_CLASSES'': (''rest_framework.permissions.AllowAny'',),
    ''PAGINATE_BY'': 10
}

ROOT_URLCONF = ''myproject.urls''

WSGI_APPLICATION = ''myproject.wsgi.application''

# Localization ant timezone settings

TIME_ZONE = ''UTC''  
USE_TZ = True

CELERY_ENABLE_UTC = True  
CELERY_TIMEZONE = "UTC"

LANGUAGE_CODE = ''en-us''  
USE_I18N = True  
USE_L10N = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = ''/static/''

# Database Condocker-composeuration
DATABASES = {  
    ''default'': {
        ''ENGINE'': ''django.db.backends.postgresql_psycopg2'',
        ''NAME'': os.environ.get(''DB_ENV_DB'', ''postgres''),
        ''USER'': os.environ.get(''DB_ENV_POSTGRES_USER'', ''postgres''),
        ''PASSWORD'': os.environ.get(''DB_ENV_POSTGRES_PASSWORD'', ''postgres''),
        ''HOST'': os.environ.get(''DB_PORT_5432_TCP_ADDR'', ''db''),
        ''PORT'': os.environ.get(''DB_PORT_5432_TCP_PORT'', ''''),
    },
}

# Redis

REDIS_PORT = 6379  
REDIS_DB = 0  
REDIS_HOST = os.environ.get(''REDIS_PORT_6379_TCP_ADDR'', ''redis'')

RABBIT_HOSTNAME = os.environ.get(''RABBIT_PORT_5672_TCP'', ''rabbit'')

if RABBIT_HOSTNAME.startswith(''tcp://''):  
    RABBIT_HOSTNAME = RABBIT_HOSTNAME.split(''//'')[1]

BROKER_URL = os.environ.get(''BROKER_URL'',  
                            '''')
if not BROKER_URL:  
    BROKER_URL = ''amqp://{user}:{password}@{hostname}/{vhost}/''.format(
        user=os.environ.get(''RABBIT_ENV_USER'', ''admin''),
        password=os.environ.get(''RABBIT_ENV_RABBITMQ_PASS'', ''mypass''),
        hostname=RABBIT_HOSTNAME,
        vhost=os.environ.get(''RABBIT_ENV_VHOST'', ''''))

# We don''t want to have dead connections stored on rabbitmq, so we have to negotiate using heartbeats
BROKER_HEARTBEAT = ''?heartbeat=30''  
if not BROKER_URL.endswith(BROKER_HEARTBEAT):  
    BROKER_URL += BROKER_HEARTBEAT

BROKER_POOL_LIMIT = 1  
BROKER_CONNECTION_TIMEOUT = 10

# Celery configuration

# configure queues, currently we have only one
CELERY_DEFAULT_QUEUE = ''default''  
CELERY_QUEUES = (  
    Queue(''default'', Exchange(''default''), routing_key=''default''),
)

# Sensible settings for celery
CELERY_ALWAYS_EAGER = False  
CELERY_ACKS_LATE = True  
CELERY_TASK_PUBLISH_RETRY = True  
CELERY_DISABLE_RATE_LIMITS = False

# By default we will ignore result
# If you want to see results and try out tasks interactively, change it to False
# Or change this setting on tasks level
CELERY_IGNORE_RESULT = True  
CELERY_SEND_TASK_ERROR_EMAILS = False  
CELERY_TASK_RESULT_EXPIRES = 600

# Set redis as celery result backend
CELERY_RESULT_BACKEND = ''redis://%s:%d/%d'' % (REDIS_HOST, REDIS_PORT, REDIS_DB)  
CELERY_REDIS_MAX_CONNECTIONS = 1

# Don''t use pickle as serializer, json is much safer
CELERY_TASK_SERIALIZER = "json"  
CELERY_ACCEPT_CONTENT = [''application/json'']

CELERYD_HIJACK_ROOT_LOGGER = False  
CELERYD_PREFETCH_MULTIPLIER = 1  
CELERYD_MAX_TASKS_PER_CHILD = 1000  

Those settings will configure the Django app so that it will discover the PostgreSQL database, Redis cache, and Celery.

Now, it''s time to connect Celery to the app. Create a file celeryconf.py and paste in this code:

myproject/celeryconf.py

import os

from celery import Celery  
from django.conf import settings

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")

app = Celery(''myproject'')

CELERY_TIMEZONE = ''UTC''

app.config_from_object(''django.conf:settings'')  
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)  

That should be enough to connect Celery to our app, so the run_X scripts will work. You can read more about first steps with Django and Celery here.

Defining tasks

Celery looks for tasks inside the tasks.py file in each Django app. Usually, tasks are created either with a decorator, or by inheriting the Celery Task Class.

Here''s how you can create a task using decorator:

@app.task
def power(n):  
    """Return 2 to the n''th power"""
    return 2 ** n

And here''s how you can create a task by inheriting after the Celery Task Class:

class PowerTask(app.Task):  
    def run(self, n):
    """Return 2 to the n''th power"""
        return 2 ** n

Both are fine and good for slightly different use cases.

myproject/tasks.py

from functools import wraps

from myproject.celeryconf import app  
from .models import Job

# decorator to avoid code duplication

def update_job(fn):  
    """Decorator that will update Job with result of the function"""

    # wraps will make the name and docstring of fn available for introspection
    @wraps(fn)
    def wrapper(job_id, *args, **kwargs):
        job = Job.objects.get(id=job_id)
        job.status = ''started''
        job.save()
        try:
            # execute the function fn
            result = fn(*args, **kwargs)
            job.result = result
            job.status = ''finished''
            job.save()
        except:
            job.result = None
            job.status = ''failed''
            job.save()
    return wrapper


# two simple numerical tasks that can be computationally intensive

@app.task
@update_job
def power(n):  
    """Return 2 to the n''th power"""
    return 2 ** n


@app.task
@update_job
def fib(n):  
    """Return the n''th Fibonacci number.
    """
    if n < 0:
        raise ValueError("Fibonacci numbers are only defined for n >= 0.")
    return _fib(n)


def _fib(n):  
    if n == 0 or n == 1:
        return n
    else:
        return _fib(n - 1) + _fib(n - 2)

# mapping from names to tasks

TASK_MAPPING = {  
    ''power'': power,
    ''fibonacci'': fib
}

Building an API for scheduling tasks

If you have tasks in your system, how do you run them? In this section, you''ll create a user interface for job scheduling. In a backend application, the API will be your user interface. Let''s use the Django REST Framework for your API.

To make it as simple as possible, your app will have one model and only one ViewSet (endpoint with many HTTP methods).

Create your model, called Job, in myproject/models.py.

from django.db import models


class Job(models.Model):  
    """Class describing a computational job"""

    # currently, available types of job are:
    TYPES = (
        (''fibonacci'', ''fibonacci''),
        (''power'', ''power''),
    )

    # list of statuses that job can have
    STATUSES = (
        (''pending'', ''pending''),
        (''started'', ''started''),
        (''finished'', ''finished''),
        (''failed'', ''failed''),
    )

    type = models.CharField(choices=TYPES, max_length=20)
    status = models.CharField(choices=STATUSES, max_length=20)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    argument = models.PositiveIntegerField()
    result = models.IntegerField(null=True)

    def save(self, *args, **kwargs):
        """Save model and if job is in pending state, schedule it"""
        super(Job, self).save(*args, **kwargs)
        if self.status == ''pending'':
            from .tasks import TASK_MAPPING
            task = TASK_MAPPING[self.type]
            task.delay(job_id=self.id, n=self.argument)

Then create a serializerview, and URL configuration to access it.

myproject/serializers.py

from rest_framework import serializers

from .models import Job


class JobSerializer(serializers.HyperlinkedModelSerializer):  
    class Meta:
        model = Job

myproject/views.py

from rest_framework import mixins, viewsets

from .models import Job  
from .serializers import JobSerializer


class JobViewSet(mixins.CreateModelMixin,  
                 mixins.ListModelMixin,
                 mixins.RetrieveModelMixin,
                 viewsets.GenericViewSet):
    """
    API endpoint that allows jobs to be viewed or created.
    """
    queryset = Job.objects.all()
    serializer_class = JobSerializer

myproject/urls.py

from django.conf.urls import url, include  
from rest_framework import routers

from myproject import views


router = routers.DefaultRouter()  
# register job endpoint in the router
router.register(r''jobs'', views.JobViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [  
    url(r''^'', include(router.urls)),
    url(r''^api-auth/'', include(''rest_framework.urls'', namespace=''rest_framework''))
]

For completeness, there is also myproject/wsgi.py, defining WSGI config for the project:

import os  
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")

from django.core.wsgi import get_wsgi_application  
application = get_wsgi_application()  

and manage.py

#!/usr/bin/env python
import os  
import sys

if __name__ == "__main__":  
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

Leave __init__.py empty.

That''s all. Uh... lots of code. Luckily, everything is on GitHub, so you can just fork it.

Running the setup

Since everything is run from Docker Compose, make sure you have both Docker and Docker Compose installed before you try to start the app:

$ cd /path/to/myproject/where/is/docker-compose.yml
$ docker-compose build
$ docker-compose up

The last command will start five different containers, so just start using your API and have some fun with Celery in the meantime.

Accessing the API

Navigate in your browser to 127.0.0.1:8000 to browse your API and schedule some jobs.

Scale things out

Currently, we have only one instance of each container. We can get information about our group of containers with the docker-compose ps command.

$ docker-compose ps
           Name                          Command               State                                        Ports                                      
------------------------------------------------------------------------------------------------------------------------------------------------------
dockerdjangocelery_db_1       /docker-entrypoint.sh postgres   Up      0.0.0.0:5432->5432/tcp  
dockerdjangocelery_rabbit_1   /docker-entrypoint.sh rabb ...   Up      0.0.0.0:15672->15672/tcp, 25672/tcp, 4369/tcp, 5671/tcp, 0.0.0.0:5672->5672/tcp  
dockerdjangocelery_redis_1    /entrypoint.sh redis-server      Up      6379/tcp  
dockerdjangocelery_web_1      ./run_web.sh                     Up      0.0.0.0:8000->8000/tcp  
dockerdjangocelery_worker_1   ./run_celery.sh                  Up  

Scaling out a container with docker-compose is extremely easy. Just use the docker-compose scale command with the container name and amount:

$ docker-compose scale worker=5
Creating and starting dockerdjangocelery_worker_2 ... done  
Creating and starting dockerdjangocelery_worker_3 ... done  
Creating and starting dockerdjangocelery_worker_4 ... done  
Creating and starting dockerdjangocelery_worker_5 ... done  

Output says that docker-compose just created an additional four worker containers for us. We can double-check it with the docker-compose ps command again:

$ docker-compose ps
           Name                          Command               State                                        Ports                                      
------------------------------------------------------------------------------------------------------------------------------------------------------
dockerdjangocelery_db_1       /docker-entrypoint.sh postgres   Up      0.0.0.0:5432->5432/tcp  
dockerdjangocelery_rabbit_1   /docker-entrypoint.sh rabb ...   Up      0.0.0.0:15672->15672/tcp, 25672/tcp, 4369/tcp, 5671/tcp, 0.0.0.0:5672->5672/tcp  
dockerdjangocelery_redis_1    /entrypoint.sh redis-server      Up      6379/tcp  
dockerdjangocelery_web_1      ./run_web.sh                     Up      0.0.0.0:8000->8000/tcp  
dockerdjangocelery_worker_1   ./run_celery.sh                  Up  
dockerdjangocelery_worker_2   ./run_celery.sh                  Up  
dockerdjangocelery_worker_3   ./run_celery.sh                  Up  
dockerdjangocelery_worker_4   ./run_celery.sh                  Up  
dockerdjangocelery_worker_5   ./run_celery.sh                  Up  

You''ll see there five powerful Celery workers. Nice!

Summary

Congrats! You just married Django with Celery to build a distributed asynchronous computation system. I think you''ll agree it was pretty easy to build an API, and even easier to scale workers for it! However, life isn''t always so nice to us, and sometimes we have to troubleshoot.

Contribution

Original article written by Justyna Ilczuk, updated by Michał Kobus.

 ENGINEERING | DOCKER | CELERY | DJANGO | DOCKER COMPOSEShare:     

 

今天关于Docker Golang客户端ContainerAttach在阅读器中返回标准输入golang docker api的分享就到这里,希望大家有所收获,若想了解更多关于A human-machine collaboration to defend against cyberattacks、Basic concepts of docker/kubernete/kata-container、centos rancher 通过本机 docker images 新增 container、Configuring and Running Django + Celery in Docker Containers等相关知识,可以在本站进行查询。

本篇文章给大家谈谈在RXJS Tap操作符中时,不会执行Console.Log,以及rxjava的操作符的知识点,同时本文还将给你拓展angular升@^6版本依赖rxjs@^6中rxjs@^6版本中操作符和静态方法报错并改正、Azure 监控诊断设置 AppServiceConsoleLogs 未显示所有 console.log 行、collections被修改; 枚举操作可能不会执行、console.dir和console.log有什么区别?等相关知识,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

在RXJS Tap操作符中时,不会执行Console.Log(rxjava的操作符)

在RXJS Tap操作符中时,不会执行Console.Log(rxjava的操作符)

您可能缺少订阅。所有rxjs事情都是懒惰的,除非完成订阅,否则它们将不会运行。如果您除了tap运算符之外不需要其他方式处理结果,只需在末尾添加.subscribe()

zip(...).pipe(
  tap(...)
).subscribe();

angular升@^6版本依赖rxjs@^6中rxjs@^6版本中操作符和静态方法报错并改正

angular升@^6版本依赖rxjs@^6中rxjs@^6版本中操作符和静态方法报错并改正

最近公司要把angular项目升级到最新版本,简单升级后系统是运行不起来的,其中就有rxjs的引入报错和rxjs一些操作符和静态方法的报错,花了一些时间排查rxjs的错误,下面就列举Observable 静态方法和操作符引用错误及解决方法和小伙伴分享一下,帮助小伙伴节省排查时间,方便小伙伴举一反三,有不正确的地方欢迎小伙伴雅正。

rxjx@^5.0.0版本Observable、静态方法、操作符的引用方法在@^6中报的错误

import {Observable} from "rxjs/Observable";
import "rxjs/add/Observable/fromEvent";
import "rxjs/add/operator/map";
ERROR in node_modules/rxjs/Observable.d.ts(1,15): error TS2307: Cannot find module ''rxjs-compat/Observable''.
src/app/common/services/http/api.ts(7,9): error TS2305: Module ''"F:/exercises/myNG/node_modules/rxjs/Observable"'' has no exported member ''Observable''.

ERROR in ./node_modules/rxjs/add/Observable/fromEvent.js
Module not found: Error: Can''t resolve ''rxjs-compat/add/observable/fromEvent'' in ''F:\exercises\myNG\node_modules\rxjs\add\Observable''

ERROR in ./node_modules/rxjs/add/Observable/fromEvent.js
Module not found: Error: Can''t resolve ''rxjs-compat/add/observable/fromEvent'' in ''F:\exercises\myNG\node_modules\rxjs\add\Observable''

rxjx@^6.0.0中的正确引用方法

import {Observable} from "rxjs/index"import {Observable} from "rxjs"这两种引用都是正确的,但是在webStorm中的第二种方法会有错误信息的提示,但是可以正常编译,因为编译的时候对象会自动检索rxjs文件夹下的index.d.ts文件,但是webStorm在显示的时候不会去检索,rxjs只是一个文件夹。
import {Observable} from "rxjs/index"; //Observable
import {fromEvent} from "rxjs/index";  //静态方法
import { map } from "rxjs/operators";  //操作符

注意:正确的引用还没有完,静态方法和操作符使用方法还有变化,下面是rxjs@^5版本的实用方法及报错信息

Observable.fromEvent(someDocumen, "someEvent").startWith(0).map()
ERROR in src/.... Property ''fromEvent'' does not exist on type ''typeof Observable''.  
 
ERROR in src/....: error TS2339: Property ''startWith'' does not exist on type ''Observable<Event>''.

ERROR in src/....: error TS2339: Property ''map'' does not exist on type ''Observable<Event>''.

rxjs@^6版本的正确使用方法

静态方法直接调用就可以了,比以前版本方便不少,但是这个操作符要吐槽一下,完全没有以前的链式写法用着方便,看着舒服,理解着容易,差评!差评!!
fromEvent(someDocumen, "someEvent").pipe(
    startWith(0),
    map()
)

?catch操作符更名为catchError
?throw操作符更名为throwError

欢迎小伙伴点个赞 ??????????????????

Azure 监控诊断设置 AppServiceConsoleLogs 未显示所有 console.log 行

Azure 监控诊断设置 AppServiceConsoleLogs 未显示所有 console.log 行

如何解决Azure 监控诊断设置 AppServiceConsoleLogs 未显示所有 console.log 行?

我们已经设置了 Azure 诊断设置(预览版)AppServiceConsoleLogs 来记录我们所有的 nodejs console.log() 行。这些文件既存储在 Log Analytics 工作区中,又存档到我们的 Azure 存储帐户中。

我注意到它确实从我们的 node.js 应用程序中捕获了许多 console.log() 行。然而,远非如此。它似乎是随机的 - 一些 console.log 行被捕获,而另一些则没有。我猜它在 nodejs 代码中捕获了大约 10-25% 的 console.log 行。

我在网上看到,“信息”(或“信息”)和“详细”是有区别的。事实上,在查询工具中,有一个“级别”列,在我的中它只有“信息”行。 但是,我在设置中没有看到可以选择“详细”的地方。

这是我们如何设置屏幕截图...

在应用服务中,在“监控”和“诊断设置(预览)...

enter image description here

然后,点击“编辑设置”,我们有...

enter image description here

然后,当我在 DefaultWorkspace 中单击“搜索和分析日志”下的“查看日志”,然后选择“AppServiceConsoleLogs”时,我得到了这个屏幕,它清楚地显示了我们应用程序的一些 console.logs(例如在顶部圈出 - “从 orderH____ 得到了订单”)。但远不及所有的 console.logs。同样圈出,级别是“信息”。当我点击过滤器并选择“不等于”“信息”时,它什么也没显示。

enter image description here

如果我导出到 CSV 并查看它 - 当然,同样的事情。

我找不到任何地方告诉它我想记录“详细”而不是“信息”。

也许作为旁注,以下是我们的“监控应用服务日志”屏幕的外观/设置方式。 “应用程序日志记录”为“关闭”。我会打开它以尝试查看它是否有所作为,但是由于它已经记录了我们的一些 console.logs,并且当我单击“文件系统”时,它没有显示任何有关“详细”日志记录的信息,除非我真的知道自己在做什么,否则我宁愿不尝试。

enter image description here

解决方法

我最终弄清楚了这一点。

我确实需要将“应用程序日志记录”从“关闭”打开到“文件系统”(请参阅​​我问题末尾的上方)。即使没有“信息”与“详细”设置(显然 Azure 摆脱了该设置,只是将其默认为“详细”??),它现在为我提供了非常详细的日志 - 我所有的 console.logs 加上更多!

然后我从“监控”下的侧边栏中转到“诊断设置(预览)”。然后单击“defaultworkspace”链接。然后单击“DefaultWorkspace”屏幕底部“搜索和分析日志”下的“查看日志”。

然后,这会将您带到一个屏幕,其中包含许多您可以运行的预定义查询,或者您只需单击“x”并在过去 24 小时内或您想要的任何时间范围内运行对日志的查询!

collections被修改; 枚举操作可能不会执行

collections被修改; 枚举操作可能不会执行

我收到错误:收集被修改; 枚举操作可能无法执行。 我试图删除所有打开的窗体对象,而不是当前的窗体对象:

FormCollection fc = Application.OpenForms; foreach (Form form in fc) { if (form.ToString().Contains("_MainFrom.Form1")) { // Do nothing } else { form.Hide(); form.dispose(); } }

C#/。NET:从回收站中的文件中检索内容/文件属性

C#:没有完全扩展的环境variables?

我如何使用“networking服务”帐户启动控制台应用程序

exception错误对话框

将进程或模块标识为托pipe/本地

枚举不能修改集合。

(使用foreach (Form form in fc.Cast<Form>().ToList())

更改

foreach (Form form in fc)

foreach (Form form in fc.OfType<Form>().ToList())

这样,在开始从原始集合中删除东西之前,您正在将OpenForms集合复制到新的集合中。

你不能修改你正在执行枚举的集合(例如foreach )。 您应该在这里使用其他方法,如Remove或使用循环。

你的问题是:“我正在通过关闭其中一个表单来修改Open表单的集合,并且在迭代时正在修改Open表单集合的错误。”

答案:要么不使用foreach迭代,要么在迭代过程中不要修改集合。 否则,他们会发现。

最常见的做法是将这样的操作分成两个步骤:

找到需要添加/从集合中删除的对象

对结果收集的对象采取行动

在你的情况下:

var toClose = fc.Where( form => form.GetType().FullName.Contains("_MainFrom.Form1")); toClose.ToList().ForEach(form => { form.Hide(); form.dispose(); });

console.dir和console.log有什么区别?

console.dir和console.log有什么区别?

如何解决console.dir和console.log有什么区别??

在Firefox中,这些功能的行为有很大不同:log仅打印toString表示形式,而dir打印出可导航树。

在Chrome中, 大多数情况下log已经打印出一棵树。但是,Chrome 仍然对某些类别的对象进行字符串化,即使它们具有属性。也许最清楚的例子是正则表达式: __log

> console.log(/foo/);
/foo/

> console.dir(/foo/);
* /foo/
    global: false
    ignoreCase: false
    lastIndex: 0
    ...

您还可以看到与普通对象不同的数组(例如console.dir([1,2,3]))的明显区别log

> console.log([1,2,3])
[1, 2, 3]

> console.dir([1,2,3])
* Array[3]
    0: 1
    1: 2
    2: 3
    length: 3
    * __proto__: Array[0]
        concat: function concat() { [native code] }
        constructor: function Array() { [native code] }
        entries: function entries() { [native code] }
        ...

解决方法

在Chrome中,console对象定义了两个似乎做同样事情的方法:

console.log(...)
console.dir(...)

我在某处在线阅读,dir在记录该对象之前先获取了该对象的副本,而log只是将引用传递给控制台,这意味着到您检查记录的对象时,它可能已更改。但是,一些初步测试表明,两者没有什么区别,而且它们都可能以与记录时不同的状态显示对象。

在Chrome控制台(Ctrl+ Shift+ J)中尝试此操作,以了解我的意思:

> o = { foo: 1 }
> console.log(o)
> o.foo = 2

现在,展开[Object]下面的log语句,注意它显示foo的值为2。如果使用dir代替重复实验,则同样如此log

我的问题是,为什么这两个看似相同的功能存在console

关于在RXJS Tap操作符中时,不会执行Console.Logrxjava的操作符的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于angular升@^6版本依赖rxjs@^6中rxjs@^6版本中操作符和静态方法报错并改正、Azure 监控诊断设置 AppServiceConsoleLogs 未显示所有 console.log 行、collections被修改; 枚举操作可能不会执行、console.dir和console.log有什么区别?的相关知识,请在本站寻找。

关于如何将onChange与react hook结合在react select上以根据用户选择更改数据库的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于(React) useDispatch TypeError: Object(...) is not a function handleChange、onChange 不适用于 React Native,但适用于 React JS、onChange函数不适用于带有react-rails的erb中的react组件、React Hook "useState" 不能在顶层调用 React Hooks 必须在 React 函数组件或自定义 React Hook 函数中调用等相关知识的信息别忘了在本站进行查找喔。

本文目录一览:

如何将onChange与react hook结合在react select上以根据用户选择更改数据库

如何将onChange与react hook结合在react select上以根据用户选择更改数据库

您实际上应该将大多数函数定义放在render方法之外,因为每次渲染组件时,都会重新创建所有函数,这是不必要的,并且很容易避免。

无论如何,我重构了您的代码,现在看起来像这样。

const defaultDate = options[0];
const defaultData = {};

export default function App() {
  const [date,setDate] = React.useState(defaultDate.value);
  const [chartData,setChartData] = useState(defaultData);

  const handleChange = (value) => {
    const date = value.value;
    setDate(date);
  };

  React.useEffect(() => {
    getDataFromDate(date).then((chartData) => {
      setChartData(chartData);
    });
  },[date]);

  return (
    <div className="card-one">
      <span className="dropdown-select">
        <Select
          options={options}
          onChange={handleChange}
        />
      </span>
      <Bar
        data={chartData}
        {...}
      />
    </div>
  );
}

大多数函数和变量都可以像这样放置在函数主体之外。

const options = [
  { label: "last hour",value: "hour" },{ label: "last day",value: "day" },{ label: "last week",value: "week" },{ label: "last month",value: "month" },{ label: "last year",value: "year" }
];

const getRandomColors = (numOfBars) => {
  const letters = "0123456789ABCDEF".split("");
  let colors = [];
  for (let i = 0; i < numOfBars; i++) {
    let color = "#";
    for (let k = 0; k < 6; k++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    colors.push(color);
  }
  return colors;
};

function requestApi(date) {
  const labels = [9876,4245,2345,3452,6534];
  let result;

  switch (date) {
    case "hour":
      result = {
        labels,datasets: [
          {
            label: "Agent performance",data: [3428,8743,5748,4675,9265],backgroundColor: getRandomColors(labels.length),borderWidth: 2
          }
        ]
      };
      break;

    case "day":
      result = {
        labels,data: [3454,4555,4554,5454,4542,6543,3445,4567],borderWidth: 2
          }
        ]
      };
      break;
    default:
      break;
  }
  return Promise.resolve(result);
}

function getDataFromDate(date) {
  return requestApi(date);
}

function customTheme(theme) {
  return {
    ...theme,colors: {
      ...theme.colors,primary25: "#43425d",primary: "#3c4a64"
    }
  };
}

实时示例

Edit 63925910/how-to-use-onchange-with-react-hook-on-react-select-to-change-data-base-on-user

(React) useDispatch TypeError: Object(...) is not a function handleChange

(React) useDispatch TypeError: Object(...) is not a function handleChange

如何解决(React) useDispatch TypeError: Object(...) is not a function handleChange?

我正在做一个简单的 React 应用程序,其中任何用户在输入文本中引入一个文本,它会自动更新商店中的状态。 这是 React 的非常简单的实践,但我对这个错误感到非常挣扎和沮丧,因为我尝试了所有方法,但仍然遇到同样的问题。

我正在使用“react-redux”和“@reduxjs/toolkit”依赖项。我尝试了所有方法,检查并比较了类似问题的类似示例和解决方案,我从头开始重新制作了该应用程序,以确保不同版本的依赖项没有任何问题,并且我尝试使我的代码非常简单它有效,但无效。

我希望你们中的任何人都可以给我建议或解决方案。 谢谢!!

错误

TypeError: Object(...) is not a function
handleChange
C:/Users/Ruben/Desktop/Projects/React/reddit2/reddit/src/features/search/SearchBar.js:14
  11 | 
  12 | 
  13 |  const handleChange = (e) => {
> 14 |    dispatch(setSearchTerm(e.target.value))
     | ^  15 |  }
  16 | 
  17 | 
View compiled
▶ 19 stack frames were collapsed.
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.  Click the ''X'' or hit ESC to dismiss this message.

这些是文件:

SearchBar 组件

import React from "react";
import {usedispatch,useSelector} from "react-redux";
import {setSearchTerm,selectSearchTerm} from "../search/searchSlice";


export const SearchBar = () => {
  
  
  const dispatch = usedispatch();
  const term = useSelector(selectSearchTerm);


  const handleChange = (e) => {
    dispatch(setSearchTerm(e.target.value))
  }


  return(
    <div>
      <input
        id="search"
        type="text"
        value={term}
        onChange={handleChange}
        placeholder="Introduce your Topic"
        />
    </div>
  );
};

searchSlice

import {createSlice} from "@reduxjs/toolkit";


export const searchSlice = createSlice({
  name: ''search'',initialState: '''',reducer: {
    setSearchTerm: (state,action) => {state.search = action.payload},}
});

export const {setSearchTerm} = searchSlice.actions;

export const selectSearchTerm = (state) => state.search;

export default searchSlice.reducer;

商店

import {configureStore} from "@reduxjs/toolkit";
import searchReducer from "../features/search/searchSlice";

export default configureStore({
  reducer: {
    search: searchReducer,},});

索引

import React from ''react'';
import ReactDOM from ''react-dom'';
import { Provider } from "react-redux";
import ''./index.css'';
import App from ''../src/App/App'';
import reportWebVitals from ''./reportWebVitals'';
import store from "../src/App/store";

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>  
  </React.StrictMode>,document.getElementById(''root'')
);

Package.json

{
  "name": "reddit","version": "0.1.0","private": true,"dependencies": {
    "@reduxjs/toolkit": "^1.5.1","@testing-library/jest-dom": "^5.13.0","@testing-library/react": "^11.2.7","@testing-library/user-event": "^12.8.3","react": "^17.0.2","react-dom": "^17.0.2","react-redux": "^7.2.4","react-scripts": "4.0.3","web-vitals": "^1.1.2"
  },

解决方法

问题

  1. 您在 createSlice 中有一个拼写错误,正确的键是 reducers,带有“s”,而不是 reducer。这导致切片操作实际上未定义。
  2. 您的状态不太正确。它不是一个可起草的对象。

解决方案

更正reducer key并提供正确的状态。

export const searchSlice = createSlice({
  name: "search",initialState: { search: "" },// <-- object state
  reducers: {
    setSearchTerm: (state,action) => {
      state.search = action.payload; // <-- update property
    }
  }
});

export const { setSearchTerm } = searchSlice.actions;

export const selectSearchTerm = (state) => state.search.search; // <-- select property

export default searchSlice.reducer;

Edit react-usedispatch-typeerror-object-is-not-a-function-handlechange

onChange 不适用于 React Native,但适用于 React JS

onChange 不适用于 React Native,但适用于 React JS

如何解决onChange 不适用于 React Native,但适用于 React JS?

onChange ={ (e) => setName(e.target.value) }

const [name,setName] = useState(""); 它不在 React Native 中工作,但同时在 React JS 中工作。我也使用 onChangeText,它也不起作用

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

onChange函数不适用于带有react-rails的erb中的react组件

onChange函数不适用于带有react-rails的erb中的react组件

在元素上尝试使用onInput代替onChange标签,这可能会按照您想要的方式工作。

,

将组件安装到.erb上的方式可能有问题。我创建了一个repo来演示如何在您的项目中正确设置react-rails。要处理搜索/过滤器功能,请查看此commit。

简而言之,

  1. 确保将正确的组件名称传递到react_components上。就我而言,我通过了App作为主要组成部分。参见here。
  2. 确保自动导出所有组件。在这种情况下,请按here所示使用react_ujs。我的组件文件夹名称是components,这就是为什么我使用const componentRequireContext = require.context('components',true);

React Hook

React Hook "useState" 不能在顶层调用 React Hooks 必须在 React 函数组件或自定义 React Hook 函数中调用

你不能在顶层调用 React Hooks,你需要创建一个函数式组件。

详细了解组件 here 和挂钩 here。

一个功能组件看起来像这样:

import React,{ useState } from 'react';

// Create your functional component:
function Example() {
  // And now you can use hooks
  // But only inside your functional component's
  // body
  const [count,setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

关于如何将onChange与react hook结合在react select上以根据用户选择更改数据库的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于(React) useDispatch TypeError: Object(...) is not a function handleChange、onChange 不适用于 React Native,但适用于 React JS、onChange函数不适用于带有react-rails的erb中的react组件、React Hook "useState" 不能在顶层调用 React Hooks 必须在 React 函数组件或自定义 React Hook 函数中调用等相关知识的信息别忘了在本站进行查找喔。

本文标签: